开发者

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

开发者 https://www.devze.com 2023-01-09 10:19 出处:网络
Using PHP 5.3.3 (stable) on Linux CentOS 5.5. Here\'s my folder structur开发者_Go百科e: www/myFolder/

Using PHP 5.3.3 (stable) on Linux CentOS 5.5.

Here's my folder structur开发者_Go百科e:

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?


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


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

$scan = scandir('myFolder');

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


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


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'; 
    } 
} 


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

精彩评论

暂无评论...
验证码 换一张
取 消