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

十年热恋 提交于 2019-12-07 10:26:51

问题


Using PHP 5.3.3 (stable) on Linux CentOS 5.5.

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:

.
..
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?


回答1:


You need to change directory or append it to your test. is_dir returns false when the file doesn't exist.

$scan = scandir('myFolder');

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

That should do the right thing




回答2:


Doesn't is_dir() take a file as a parameter?

$scan = scandir('myFolder');

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



回答3:


Already told you the answer here: http://bugs.php.net/bug.php?id=52471




回答4:


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()

$scan = scandir('myFolder'); 

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



回答5:


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);


来源:https://stackoverflow.com/questions/3353853/php-using-scandir-folders-are-treated-as-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!