savita
savita

Reputation: 41

Complete list of files and folders in remote server via SFTP

How to list all files recursively in remote server via SFTP in PHP?

opendir or scandir only list in current folder.

Upvotes: 0

Views: 7265

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202494

phpseclib library has recursive listing built-in, just use Net_SFTP.nlist() with $recursive = true:

set_include_path(get_include_path() . PATH_SEPARATOR . 'phpseclib');
require_once("Net/SFTP.php");

$sftp = new Net_SFTP($hostname);

if (!$sftp->login($username, $password))
{
    die("Cannot login to the server");
}

if (!($files = $sftp->nlist($path, true)))
{
    die("Cannot read directory contents");
}

foreach ($files as $file)
{
    echo "$file\n";
}

If you need to list even the folder names (so that you capture even empty folder), you have to re-implement, what nlist does:

function nlist_with_folders($sftp, $dir)
{
    $files = $sftp->rawlist($dir);
    if ($files === false)
    {
        $result = false;
    }
    else
    {
        $result = array();
        foreach ($files as $name => $attrs)
        {
            if (($name != ".") && ($name != ".."))
            {
                $path = "$dir/$name";
                $result[] = $path;
                if ($attrs["type"] == NET_SFTP_TYPE_DIRECTORY)
                {
                    $sub_files = nlist_with_folders($sftp, $path);
                    $result = array_merge($result, $sub_files);
                }
            }
        }
    }

    return $result;
}

The following was/is true about phpseclib 1.0 branch, whose latest release 1.0.19 from 2020 is still usable, but it does not seem to be updated anymore. The phpseclib 2.0 and 3.0 use Composer, so their setup is somewhat more complicated.

phpseclib does not require any installation and does not have any mandatory dependencies. It's a "pure PHP" code. You just download an archive with the PHP code and extract it to your webserver (or extract it locally and upload the extracted code, if you do not have a shell access to the webserver). In my example, I have extracted it to phpseclib subfolder.

Upvotes: 5

Related Questions