0

我有一个脚本可以打开一个目录,检查文件夹是否与数组匹配,然后打开它们。在该目录中有一个文件夹列表,例如“apache2-50”,但是当脚本打开该文件夹时,它只显示 .DS_Store 文件。这是输出:

This-is-not-a-MacBook:backend code archangel$ php -f frolic.php "/Users/archangel/Desktop/Httpbench Files/results"
Test Found apache2 in directory /Users/archangel/Desktop/Httpbench Files/results/apache2-50
--/Users/archangel/Desktop/Httpbench Files/results/apache2-50/.DS_Store

但这里是目录列表:

This-is-not-a-MacBook:apache2-50 archangel$ ls
0   1   2

现在我想弄清楚为什么我的 php 脚本没有显示这些文件夹。当我将文件夹“0”更改为“3”时,它可以工作:

This-is-not-a-MacBook:apache2-50 archangel$ ls
1   2   3

This-is-not-a-MacBook:backend code archangel$ php -f frolic.php "/Users/archangel/Desktop/Httpbench Files/results"
Test Found apache2 in directory /Users/archangel/Desktop/Httpbench Files/results/apache2-50
--/Users/archangel/Desktop/Httpbench Files/results/apache2-50/.DS_Store
--/Users/archangel/Desktop/Httpbench Files/results/apache2-50/1
--/Users/archangel/Desktop/Httpbench Files/results/apache2-50/2
--/Users/archangel/Desktop/Httpbench Files/results/apache2-50/3

这是我正在运行的代码:

#!/bin/php

//...

$dir = opendir($argv[1]);
//Opened the directory;

while($file = readdir($dir)){
//Loops through all the files/directories in our directory;
    if($file!="." && $file != ".."){
        $f = explode("-", $file);
        if(in_array($f[0], $servers) and in_array($f[1], $tests)) {
            echo "Test Found $f[0] in directory $argv[1]/$f[0]-$f[1]\n";
            $sdir = opendir("$argv[1]/$f[0]-$f[1]");
            while($sfile = readdir($sdir)){
                if($sfile!="." && $sfile != ".."){
                    echo "--$argv[1]/$f[0]-$f[1]/$sfile\n";
                }
            }
        }
    }
}

这可能是我的脚本的问题,还是 php(PHP 5.3.3)中的错误?谢谢

4

3 回答 3

2

这是PHP中字符串"0"求值的一个(非常讨厌的)副作用。false发生这种情况时,您的while循环

while($file = readdir($dir))

会破裂。

readdir()这应该有效,因为它仅在实际返回时才会中断false

while(($file = readdir($dir)) !== false)

(显然,相应地更改两个循环,而不仅仅是外部循环。)

于 2011-01-28T01:01:43.437 回答
1

你为什么要使用opendir?我认为 glob 会更容易使用:

$files = glob("$argv[1]/*-*/*");

foreach($files as $file) {
    $parts = explode("/", $file);

    // get the directory part
    $f = explode("-", $parts[count($parts) - 2]);

    if(in_array($f[0], $servers) and in_array($f[1], $tests)) {
        echo "Test Found $f[0] in directory $argv[1]/$f[0]-$f[1]\n";
        echo "--$argv[1]/$f[0]-$f[1]/$sfile\n";
    }
}
于 2011-01-28T01:05:44.447 回答
0

代替

while($sfile = readdir($sdir)){

while(($sfile = readdir($sdir)) !== 0){

否则,当文件名为 0 时,$sfile 为“0”,即转换为 false。通过使用 !== 或 === 您强制在变量之间进行类型检查,以使“0”不等于 0。

于 2011-01-28T01:04:04.683 回答