0

I'm trying to get the absolute path of some files in a folder with PHP. I use 2 recursive functions. the first one returns all the folders and files information in an array. the second one takes this array as an argument and skips the folders and must return the absolute path of the files. but I don't know where I do wrong. the second function just returns a null array.but when I echo the results it works.

here is the code :

function scan($dir){
    $files = array();
    if(file_exists($dir)){
        foreach(scandir($dir) as $f) {

            if(!$f || $f[0] == '.') {
                continue;
            }
            if(is_dir($dir . '/' . $f)) {
                $files[] = array(
                    "name" => $f,
                    "type" => "folder",
                    "path" => $dir . '/' . $f,
                    "items" => scan($dir . '/' . $f)
                );
            }
            else {
                $files[] = array(
                    "name" => $f,
                    "type" => "file",
                    "path" => $dir . '/' . $f,
                    "dirpath" => $dir
                );
            }
        }
    }
    return $files;
}
function get_files($res)
{
    $files = array();
    foreach ($res as $re)
    {
        if($re["type"] == "folder")
        {
            get_files($re["items"]);
        }
        else
        {
            $files[] = $re["path"];
        }
    }
    return $files;
}
function print_files($res)
{
    $count = 1;
    foreach ($res as $re)
    {
        if($re["type"] == "folder")
        {
            print_files($re["items"]);
        }
        else
        {
            echo($count." - ".$re["path"]."<br>");
            $count++;
        }
    }
}

the third function works but when I try to return those results in an array with the second function it returns a null array. so the problem is my second function. What can I do about it? thank you in advance.

  • `print_files` echos the content, where `get_files` will simply call the function, you would need to use `$files = get_files($re["items"]);` – Will B. Feb 17 '19 at 06:40
  • Yes, I know and already tried this but this will put those items in the array which include folders too.I want just files to be included in the final array – Alireza Seyedzade Feb 17 '19 at 06:45

1 Answers1

2

Have you looked into SPL iterators

$Iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::UNIX_PATHS));

$files = array(); 

/*@var $file SplFileInfo*/  //<-- for Eclipse PDT, PHPStorm etc. IDE autocomplete
foreach ($Iterator as $file) {
    if ($file->isDir()) continue; 

    $files[$file->getPathname()] = $file; 
}

//returns ['somefolder/somefile.txt' => SplFileInfo Object(), ...]

Besides recursive iteration though the path, with the flag above (see FLAGS) it also converts windows \ to linux /, you can even skip the dots .. and .. In this case the dot's don't matter because they are folders (isDir) so are skipped over.

And in the above $file is a SPLFileInfo object which lets you get just the filename, the path, the extension, modified time, size etc... In otherwords many of the things you are putting in your array.

Basically this does most, if not more than what you wan't with way less code..

ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38
  • thank you, man.it works very well even faster than my code.you saved my life :X :D – Alireza Seyedzade Feb 17 '19 at 07:13
  • They are difficult to get your head around at first, because it's almost magical. But I love them... You can even do `if($file->getExtension() == 'txt')` and return only files of a given extension etc... – ArtisticPhoenix Feb 17 '19 at 07:14
  • If you really want to get fancy you can even set one up to use a Regex (regular expression) for filenames etc [RecursiveRegexIterator](http://php.net/manual/en/class.recursiveregexiterator.php). Or combine them with other iterators. – ArtisticPhoenix Feb 17 '19 at 07:20
  • SPL is a whole set of classes that were added to PHP around 5.3+ ish. http://php.net/manual/en/book.spl.php It has a lot of useful stuff. You may have used some of them without even realizing it... I haven't even mastered them all and I been doing PHP before 5.3 ... lol. – ArtisticPhoenix Feb 17 '19 at 07:24
  • I remember I was so excited when they added them then I found out that `SplFileObject` had `fgetcsv` but not `fputcsv` which was bad because there was no file handle, so you couldn't use the normal functions. But they fixed that one in like 5.4 ish... lol. – ArtisticPhoenix Feb 17 '19 at 07:29
  • man do you know how can use this on phpstorm so the autocomplete works? – Alireza Seyedzade Feb 17 '19 at 07:33
  • 1
    I use Eclipse PDT, in that for loops you can do `/*@var $file SplFileInfo*/` just before the `foreach`. Not sure if it also works in PHPstorm. – ArtisticPhoenix Feb 17 '19 at 07:35
  • @xwoman2 - I googled it, and it's the same.... https://stackoverflow.com/questions/778564/phpdoc-type-hinting-for-array-of-objects So I added it to the question, to make it's use more clear. – ArtisticPhoenix Feb 17 '19 at 07:38
  • lol:D you are my lifesaver.it need 2 * before var /** I mean.but thank you anyway. you did a lot of help today – Alireza Seyedzade Feb 17 '19 at 07:47
  • 1
    Sure I learned a lot on here, back in the day, so it's my way of saying thanks SO. – ArtisticPhoenix Feb 17 '19 at 07:54