简体   繁体   中英

PHP recursive function for printing files and directories is not working

I am trying to make recursive PHP function which will loop through tree of directories and subdirectories and put all directories and files in one array.

My code looks logical to me, but it is not working.

Tree of directories and files:

在此处输入图片说明

PHP code

    <?php
        function printFiles($directory) {
            $files = array();

            foreach (scandir($directory) as $file) {
                if ($file === '.' || $file === '..') 
                    continue;

                // checking is it file or directory
                if (is_dir($directory . '\\'. $file)) {
                    return printFiles($directory . '\\'.  $file);
                }

                array_push($files, $file);
            }

            return($files);
        }

        $directory = 'C:\Users\Jakov\Desktop\DIRECTORIES';
        print_r(printFiles($directory));

    ?>

I am getting this result:

Array ( )

You are only getting the files contained in the first deepest folder your function encounters, A_1_1 , which has no files inside.

Don't return when you find a directory. Add to current list instead:

// checking is it file or directory
if (is_dir($directory . '/'. $file)) {
    $files = array_merge($files, printFiles($directory . '/'.  $file));
} else {
    array_push($files, $file);
}

Also, use / for paths. It works in Windows and you will avoid escaping errors:

$directory = 'C:/Users/Jakov/Desktop/DIRECTORIES';

(In your code, you should be using \\\\ instead of \\ as separator.)

You should also check for links -and ignore them-, or you could get trapped in an infinite loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM