简体   繁体   中英

How to download a file from SFTP using PHP?

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?

Using phpseclib, a pure PHP SFTP implementation :

<?php
include('Net/SFTP.php');

$sftp = new Net_SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
    exit('Login Failed');
}

// outputs the contents of filename.remote to the screen
echo $sftp->get('filename.remote');
?>

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM