![](/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.