简体   繁体   中英

I'm trying to download a file from the server using sftp connection and save it on my server

I'm trying to download a file from the server using sftp connection and save it on my server but the file is empty.

$connection = ssh2_connect('{my server ip}', 22);
ssh2_auth_password($connection, '{user}', '{password}');
$sftp = ssh2_sftp($connection);
$file = "test.txt";
$target_path = "ssh2.sftp://$sftp/public_html/$file";
$stream = fopen($target_path, 'r');
fopen($file, "w");
fclose($stream);

You never copy the data between the opened files/handles. Easy way to do that is using stream_copy_to_stream :

$local_stream = fopen($file, "w");
stream_copy_to_stream($stream, $local_stream);
fclose($local_stream);

As @KenLee commented, if your server supports SCP too (most do), you can replace 6 lines of the code with simple ssh2_scp_recv :

ssh2_scp_recv($connection, "/public_html/$file", $file);

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