PHP: using scandir () folders are treated as files

Using PHP 5.3.3 (stable) on Linux CentOS 5.5.

Here is my folder structure:

www/myFolder/
www/myFolder/testFolder/
www/myFolder/testFile.txt

Using scandir () in the "myFolder" folder, I get the following results:

.
..
testFolder
testFile.txt

I am trying to filter folders from the results and only return files:

$scan = scandir('myFolder');

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

Expected results:

testFile.txt

However, I really see:

testFile.txt
testFolder

Can someone tell me what's wrong here please?

+3
source share
5 answers

You need to change the directory or add it to your test. is_dirreturns false when the file does not exist.

$scan = scandir('myFolder');

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

That should do the right thing.

+9
source

Does not is_dir () accept a file as a parameter?

$scan = scandir('myFolder');

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

, , :

Warning: Wrong parameter count for is_dir() in testFile.php on line 16

$file is_dir()

$scan = scandir('myFolder'); 

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

If someone who comes here is interested in storing the output in an array, here is a quick way to do it (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
source

Source: https://habr.com/ru/post/1756958/


All Articles