![](/img/trans.png)
[英]Should I use PHP readfile() or SFTP connection to download file from my server through a web app?
[英]I'm trying to download a file from the server using sftp connection and save it on my server
我正在嘗試使用 sftp 連接從服務器下載文件並將其保存在我的服務器上,但文件為空。
$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);
您永遠不會在打開的文件/句柄之間復制數據。 簡單的方法是使用stream_copy_to_stream
:
$local_stream = fopen($file, "w");
stream_copy_to_stream($stream, $local_stream);
fclose($local_stream);
正如@KenLee 評論的那樣,如果您的服務器也支持 SCP(大多數都支持),您可以用簡單的ssh2_scp_recv
替換 6 行代碼:
ssh2_scp_recv($connection, "/public_html/$file", $file);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.