Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

scandir

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?

like image 601
Reado Avatar asked Jul 28 '10 14:07

Reado


People also ask

What does Scandir do in PHP?

The scandir() function returns an array of files and directories of the specified directory.

How can I get a list of all the subfolders and files present in a directory using PHP?

PHP using scandir() to find folders in a directory To check if a folder or a file is in use, the function is_dir() or is_file() can be used. The scandir function is an inbuilt function that returns an array of files and directories of a specific directory.

What is __ DIR __ in PHP?

The __DIR__ can be used to obtain the current code working directory. It has been introduced in PHP beginning from version 5.3. It is similar to using dirname(__FILE__). Usually, it is used to include other files that is present in an included file.


1 Answers

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

like image 177
Cfreak Avatar answered Oct 05 '22 11:10

Cfreak