Get directory structure from FTP using PHP

1.1k views Asked by At

I have ftp server with a lot of subfolders and files in it. I need to retrieve the folder structure from ftp, which shows names of all folders and subfolders from a specified starting path. I'm not interested in files included in each folder, only the directory tree. I'm using PHP and my server does not support mlsd.

Thanks for help.

I implemented my own recursive function, which for some reason is not working.

function ftp_list_files_recursive($ftp_stream, $path) {
    $lines = ftp_rawlist($ftp_stream, $path);
    $result = [];
    if (is_array($lines) || is_object($lines)) {
        foreach ($lines as $line) {
            $exp0 = explode('<', $line);
            if (sizeof($exp0) > 1):
                $exp1 = explode('>', $exp0[1]);
                if ($exp1[0] == 'DIR') {
                    $file_path=$path . "/" . ltrim($exp1[1]);
                    $result = array_merge($result, ftp_list_files_recursive($ftp_stream, $file_path));
                } else {
                    $result[] = $file_path;
                }
            endif;
        }
    }

    return $result;
}

The ftp_rawlist returns directory info as: 01-18-20 01:00PM <DIR> DirName so first I explode on < and check whether it was successful. If yes, then it means a string had DIR in it and it can be further exploded on >. It could have been done with regular expression, but that works for me now. If I print $file_path variable I see that it changes, so I assume the recursion works. However, the $result array is always empty. Any thoughts on that?

1

There are 1 answers

0
Martin Prikryl On BEST ANSWER

Start here: PHP FTP recursive directory listing.

You just need to adjust the code to:

  1. the DOS-style listing you have from your FTP server (IIS probably) and
  2. to collect only the folders.
function ftp_list_dirs_recursive($ftp_stream, $directory)
{
    $result = [];

    $lines = ftp_rawlist($ftp_stream, $directory);
    if ($lines === false)
    {
        die("Cannot list $directory");
    }

    foreach ($lines as $line)
    {
        // rather lame parsing as a quick example:
        if (strpos($line, "<DIR>") !== false)
        {
            $dir_path = $directory . "/" . ltrim(substr($line, strpos($line, ">") + 1));
            $subdirs = ftp_list_dirs_recursive($ftp_stream, $dir_path);
            $result = array_merge($result, [$dir_path], $subdirs);
        }
    }
    return $result;
}