PHP SFTP使用ssh2破坏PDF文件


php sftp using ssh2 corrupting pdf files

我正试图通过SFTP将pdf文件从我们的服务器传输到另一个服务器。我检查了文件,它们本身并没有损坏。我可以在命令行上把它们scp到我的计算机上,它们打开得很好。注意:我可以成功地传输pdf文件,它只是损坏了一旦它到达另一个服务器。

我试过用两种方法:

conn = ssh2_connect($url, 22);
$auth = ssh2_auth_password($conn, $userName, $password);
$sftp = ssh2_sftp($conn);
file_put_contents("ssh2.sftp://".$sftp.$remoteFilePath, $localFilePath);

看完这个问题,我想到了下面的问题,并试着回答:

ssh2_scp_send()使用PHP破坏pdf

conn = ssh2_connect($url, 22);
$auth = ssh2_auth_password($conn, $userName, $password);
$sftp = ssh2_sftp($conn);
$fp = fopen("ssh2.sftp://".$sftp.$remoteFilePath, "w");
fwrite($fp, $localFilePath);
fclose($fp);

这也传输文件,但也损坏了,所以我不能打开它在我的FTP GUI一旦它在他们的服务器。

我现在知道另一个php扩展可以做到这一点。如果我不能让它工作,我会尝试它,但我已经投入了足够的时间,它应该工作。任何想法吗?

看http://php.net/manual/en/function.ssh2-scp-send.php

和尝试:

$conn = ssh2_connect($url, 22);
$auth = ssh2_auth_password($conn, $userName, $password);
ssh2_scp_send($conn, $localFilePath, $remoteFilePath, 0644);

找到答案了。我把$localFilePath写成这样:

$localFilePath = "/path/to/my/file.pdf";

file_put_contents()和fwrite()将变量视为字符串。因此,它将创建一个新的pdf文件,其内容为字符串filepath。我只是在尝试传输一个小的。txt文件后才发现这个问题。所以,添加这个修复了这个问题:

$localFilePath = fopen("/path/to/my/file.pdf", "r");

我觉得很奇怪,我没有看到这个在例子中使用,我已经看到sftp使用这种方法,但就是这样。