How to download a file from SFTP using PHP?

10,455

Once you have your SFTP connection open, you can read files and write using standard PHP functions such as fopen, fread, and fwrite. You just need to use the ssh2.sftp:// resource handler to open your remote file.

Here is an example that will scan a directory and download all files in the root folder:

// Assuming the SSH connection is already established:
$resSFTP = ssh2_sftp($resConnection);
$dirhandle = opendir("ssh2.sftp://$resSFTP/");
while ($entry = readdir($dirhandle)){
    $remotehandle = fopen("ssh2.sftp://$resSFTP/$entry", 'r');
    $localhandle = fopen("/tmp/$entry", 'w');
    while( $chunk = fread($remotehandle, 8192)) {
        fwrite($localhandle, $chunk);
    }
    fclose($remotehandle);
    fclose($localhandle);
}
Share:
10,455
SANKAR810122
Author by

SANKAR810122

Updated on August 08, 2022

Comments

  • SANKAR810122
    SANKAR810122 over 1 year

    I am trying to download a file from an sftp server using php but I can't find any correct documentation to download a file.

    <?php 
    $strServer = "pass.com"; 
    $strServerPort = "22";
    $strServerUsername = "admin"; 
    $strServerPassword = "password";
    $resConnection = ssh2_connect($strServer, $strServerPort);
    if(ssh2_auth_password($resConnection, $strServerUsername, $strServerPassword)) {
        $resSFTP = ssh2_sftp($resConnection);
        echo "success";
    }
    ?>
    

    Once I have the SFTP connection open, what do I need to do to download a file?

  • Valery Lourie
    Valery Lourie almost 7 years
    Starting from PHP5.6, this won't work and will silently fail: <pre><code> $remotehandle = fopen("ssh2.sftp://$resSFTP/$entry", 'r'); </code></pre> $resSFTP should be explicitly converted to int: <pre><code> $remotehandle = fopen('ssh2.sftp://' . intval($resSFTP) . '/$entry', 'r'); </code></pre>