繁体   English   中英

PHP:使用scandir(),文件夹被视为文件

[英]PHP: Using scandir(), folders are treated as files

在Linux CentOS 5.5上使用PHP 5.3.3(稳定版)。

这是我的文件夹结构:

www/myFolder/
www/myFolder/testFolder/
www/myFolder/testFile.txt

使用scandir()对“myFolder”文件夹我得到以下结果:

.
..
testFolder
testFile.txt

我正在尝试从结果中过滤掉文件夹,只返回文件:

$scan = scandir('myFolder');

foreach($scan as $file)
{
    if (!is_dir($file))
    {
        echo $file.'\n';
    }
}

预期结果是:

testFile.txt

但是我实际上看到了:

testFile.txt
testFolder

谁能告诉我这里出了什么问题?

您需要更改目录或将其附加到测试中。 当文件不存在时, is_dir返回false。

$scan = scandir('myFolder');

foreach($scan as $file)
{
    if (!is_dir("myFolder/$file"))
    {
        echo $file.'\n';
    }
}

那应该做对了

不是is_dir()将文件作为参数吗?

$scan = scandir('myFolder');

foreach($scan as $file)
{
    if (!is_dir($file))
    {
        echo $file.'\n';
    }
}

已经在这里告诉你答案: http//bugs.php.net/bug.php?id = 52771

如果您显示错误,您会看到为什么这不起作用:

Warning: Wrong parameter count for is_dir() in testFile.php on line 16

现在尝试将$ file传递给is_dir()

$scan = scandir('myFolder'); 

foreach($scan as $file) 
{ 
    if (!is_dir($file)) 
    { 
        echo $file.'\n'; 
    } 
} 

如果有人来这里是有兴趣将输出保存到数组,这是一个快速的方法(修改为更高效):

$dirPath = 'dashboard';

$dir = scandir($dirPath);

foreach($dir as $index => &$item)
{
    if(is_dir($dirPath. '/' . $item))
    {
        unset($dir[$index]);
    }
}

$dir = array_values($dir);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM