除了我之前的貼文之外,我發現 sftp->fopen->file_get_contents->fwrite 比 ssh2_scp_send 擁有更好的效能。
我使用了以下程式碼來測試
<?php
$srcFile = '/var/tmp/dir1/file_to_send.txt';
$dstFile = '/var/tmp/dir2/file_received.txt';
// 建立與遠端主機的連線
$conn = ssh2_connect('my.server.com', 22);
// 建立 SFTP 工作階段
$sftp = ssh2_sftp($conn);
$sftpStream = @fopen('ssh2.sftp://'.$sftp.$dstFile, 'w');
try {
if (!$sftpStream) {
throw new Exception("無法開啟遠端檔案: $dstFile");
}
$data_to_send = @file_get_contents($srcFile);
if ($data_to_send === false) {
throw new Exception("無法開啟本地檔案: $srcFile.");
}
if (@fwrite($sftpStream, $data_to_send) === false) {
throw new Exception("無法從檔案傳送資料: $srcFile.");
}
fclose($sftpStream);
} catch (Exception $e) {
error_log('例外: ' . $e->getMessage());
fclose($sftpStream);
}
?>
為了測試,我傳送了三個檔案,總大小為 6kB,傳送時間(包含連線到伺服器的時間)如下:
SFTP -> 15 秒
ssh2_scp_send -> 22 秒
謝謝,
Pimmy