Reado
Reado

Reputation: 1452

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

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?

Upvotes: 5

Views: 27387

Answers (5)

FluorescentGreen5
FluorescentGreen5

Reputation: 947

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

Upvotes: 0

Daniel Egeberg
Daniel Egeberg

Reputation: 8382

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

Upvotes: 2

Cfreak
Cfreak

Reputation: 19309

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

Upvotes: 10

Mark Baker
Mark Baker

Reputation: 212412

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

Upvotes: 1

Scott
Scott

Reputation: 4200

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

$scan = scandir('myFolder');

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

Upvotes: 2

Related Questions