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

Reado picture Reado · Jul 28, 2010 · Viewed 25k times · Source

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?

Answer

Cfreak picture Cfreak · Jul 28, 2010

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