【问题标题】:File downloaded from SFTP server using PHP fopen with ssh2.sftp:// URI is empty使用带有 ssh2.sftp:// URI 的 PHP fopen 从 SFTP 服务器下载的文件为空
【发布时间】:2022-01-05 15:31:06
【问题描述】:

我正在尝试使用 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);

【问题讨论】:

    标签: php ssh sftp


    【解决方案1】:

    您永远不会在打开的文件/句柄之间复制数据。简单的方法是使用stream_copy_to_stream:

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

    正如@KenLee 所说,如果您的服务器也支持SCP(大多数支持SFTP 的服务器都支持SCP),您可以将6 行代码替换为简单的ssh2_scp_recv

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-19
      • 2018-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多