PHP:使用 scandir(),文件夹被视为文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3353853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP: Using scandir(), folders are treated as files
提问by Reado
Using PHP 5.3.3 (stable) on Linux CentOS 5.5.
在 Linux CentOS 5.5 上使用 PHP 5.3.3(稳定版)。
Here's my folder structure:
这是我的文件夹结构:
www/myFolder/
www/myFolder/testFolder/
www/myFolder/testFile.txt
Using scandir() against the "myFolder" folder I get the following results:
对“myFolder”文件夹使用 scandir() 得到以下结果:
.
..
testFolder
testFile.txt
I'm trying to filter out the folders from the results and only return files:
我试图从结果中过滤掉文件夹,只返回文件:
$scan = scandir('myFolder');
foreach($scan as $file)
{
if (!is_dir($file))
{
echo $file.'\n';
}
}
The expected results are:
预期的结果是:
testFile.txt
However I'm actually seeing:
但是我实际上看到的是:
testFile.txt
testFolder
Can anyone tell me what's going wrong here please?
谁能告诉我这里出了什么问题?
回答by Cfreak
You need to change directory or append it to your test. is_dirreturns false when the file doesn't exist.
您需要更改目录或将其附加到您的测试中。is_dir当文件不存在时返回 false。
$scan = scandir('myFolder');
foreach($scan as $file)
{
if (!is_dir("myFolder/$file"))
{
echo $file.'\n';
}
}
That should do the right thing
那应该做正确的事
回答by Scott
Doesn't is_dir() take a file as a parameter?
is_dir() 不是将文件作为参数吗?
$scan = scandir('myFolder');
foreach($scan as $file)
{
if (!is_dir($file))
{
echo $file.'\n';
}
}
回答by Daniel Egeberg
Already told you the answer here: http://bugs.php.net/bug.php?id=52471
已经告诉你答案了:http: //bugs.php.net/bug.php?id=52471
回答by Mark Baker
If you were displaying errors, you'd see why this isn't working:
如果您显示错误,您会明白为什么这不起作用:
Warning: Wrong parameter count for is_dir() in testFile.php on line 16
Now try passing $file to is_dir()
现在尝试将 $file 传递给 is_dir()
$scan = scandir('myFolder');
foreach($scan as $file)
{
if (!is_dir($file))
{
echo $file.'\n';
}
}
回答by FluorescentGreen5
If anyone who comes here is interested in saving the output to an array, here's a fast way of doing that (modified to be more efficient):
如果来到这里的任何人都对将输出保存到数组感兴趣,这里有一个快速的方法(修改为更有效):
$dirPath = 'dashboard';
$dir = scandir($dirPath);
foreach($dir as $index => &$item)
{
if(is_dir($dirPath. '/' . $item))
{
unset($dir[$index]);
}
}
$dir = array_values($dir);

