Home » Php » file – PHP download from remote server via sftp

file – PHP download from remote server via sftp

Posted by: admin July 12, 2020 Leave a comment


This may have been asked before, I’m new to PHP and I’m trying to learn as much as I can, but this has really thrown me.

Basically what I want to know is, how would I use PHP code to get it to download everything from a remote server to a local location. It’s getting it to download everything not just one file that I’m stuck on. So please can someone show/explain to me how I would do this?

What I’ve got so far:

$connection - ssh2_connect('example.com', 22);
ssh2_auth_password($connection, 'username', 'password');


$remote ="$remote_dir";
$stream = ssh2_exec($connection, $remote);




        if(ssh2_scp_recv($connection, $remote_file,$local_file)){
            echo "File ".$file_name." was copied to $local_dir<br />"; 

I think my $remote =”$remote_dir”; is wrong, and to be honest I’ve got $filename when I want the whole directory, this is all I have so far.

How to&Answers:

Here is a small code on how to read the folder and download all its files:

$host = 'localhost';
$port = 22;
$username = 'username';
$password = 'password';
$remoteDir = '/must/be/the/complete/folder/path';
$localDir = '/can/be/the/relative/or/absolute/local/path';

if (!function_exists("ssh2_connect"))
    die('Function ssh2_connect not found, you cannot use ssh2 here');

if (!$connection = ssh2_connect($host, $port))
    die('Unable to connect');

if (!ssh2_auth_password($connection, $username, $password))
    die('Unable to authenticate.');

if (!$stream = ssh2_sftp($connection))
    die('Unable to create a stream.');

if (!$dir = opendir("ssh2.sftp://{$stream}{$remoteDir}"))
    die('Could not open the directory');

$files = array();
while (false !== ($file = readdir($dir)))
    if ($file == "." || $file == "..")
    $files[] = $file;

foreach ($files as $file)
    echo "Copying file: $file\n";
    if (!$remote = @fopen("ssh2.sftp://{$stream}/{$remoteDir}{$file}", 'r'))
        echo "Unable to open remote file: $file\n";

    if (!$local = @fopen($localDir . $file, 'w'))
        echo "Unable to create local file: $file\n";

    $read = 0;
    $filesize = filesize("ssh2.sftp://{$stream}/{$remoteDir}{$file}");
    while ($read < $filesize && ($buffer = fread($remote, $filesize - $read)))
        $read += strlen($buffer);
        if (fwrite($local, $buffer) === FALSE)
            echo "Unable to write to local file: $file\n";

You can also resume this code to (it will not copy directories):

while (false !== ($file = readdir($dirHandle)))
    if ($file == "." || $file == "..")

    echo "Copying file: $file\n";
    if(!ssh2_scp_recv($connection, $remoteDir . $file, $localDir . $file))
        echo "Could not download: ", $remoteDir, $file, "\n";

If you do not use the full path on the remote folder it will not work:



Update: I was kindly corrected that this doesn’t use sftp, but instead uses ftps. Here’s a Stackoverflow link discussing using PHP to do SFTP.

The PHP docs already cover most of what you should need for this. Here’s an example for fetching a list of the contents in the remote directory:

// set up basic connection
$ftp_server = "example.com";
$conn_id = ftp_ssl_connect($ftp_server);

// login with username and password
$ftp_user_name = "myuser";
$ftp_user_pass = "mypass";
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
ftp_pasv($conn_id, true);
// check connection
if ((!$conn_id) || (!$login_result)) {
        echo "FTP connection has failed!";
        echo "Attempted to connect to $ftp_server for user $ftp_user_name";
    } else {
        echo "Connected to $ftp_server, for user $ftp_user_name";

$buff = ftp_rawlist($conn_id, '.');