Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is_dir does not recognize folders

Tags:

directory

php

I am trying to make a function that scans a folder for subfolders and then returns a numeric array with the names of those folders.

This is the code i use for testing. Once i get it to print out the folder names and not just "." and ".." for present and above folder all will be well, and I can finish the function.

<?php
function super_l_getthemes($dir="themes")
{

if ($handle = opendir($dir)) {
    echo "Handle: {$handle}\n";
    echo "Files:\n";


    while (false !== ($file = readdir($handle))) {
       echo "{$file}<br>";
    }

    closedir($handle);
}
?>

The above code works fine, and prints out all the contents of the folder: files, subfolders and the "." and ".."

but if i replace:

  while (false !== ($file = readdir($handle))) {
       echo "{$file}<br>";
    }

with:

while (false !== ($file = readdir($handle))) {
        if(file_exists($file) && is_dir($file)){echo "{$file}";}
    }

The function only prints "." and ".." , not the two folder names that I'd like it to print.

Any help is appreciated.

like image 471
Rakoon Avatar asked Jan 22 '23 22:01

Rakoon


2 Answers

You must provide the absolute path to file_exists, otherwise it will look for it in the current execution path.

while (false !== ($file = readdir($handle))) {
    $file_path = $dir . DIRECTORY_SEPARATOR . $file;
    if (file_exists($file_path) && is_dir($file_path)) {
        echo "{$file}";
    }
}
like image 98
nuqqsa Avatar answered Jan 30 '23 02:01

nuqqsa


The problem with readdir is that it only reads the strings of the named entries inside of the directory.

For instance, if you had file "foo" inside of directory "/path/to/files/", when using readdir on "/path/to/files/", you would eventually come to the string "foo".

Normally this wouldn't be a problem if it were in the same directory as the current working directory of the script, but, since you are reading from an arbitrary director, when you are attempting to inspect the entry (file, directory, whatever), you are calling is_dir on the bare string "foo".

I would try prefixing the name you pull out using readdir with the path to the file.


if ($handle = opendir($dir)) {
    echo "Handle: {$handle}\n";
    echo "Files:\n";

    while ($file = readdir($handle)) {
        /*** make $file into an absolute path ***/
        $absolute_path = $dir . '/' . $file;

        /*** NOW try stat'ing it ***/
        if (is_dir($absolute_path)) {
            /* it's a directory; do stuff */
        }
    }

    closedir($handle);
}
like image 34
amphetamachine Avatar answered Jan 30 '23 01:01

amphetamachine