小编典典

使用SFTP上传文件

php

我已经通过ftp成功上传了文件,但是现在我需要通过SFTP进行上传。我可以成功连接到远程服务器,创建文件并写入文件,但是无法将现有文件从本地服务器上载到远程服务器。ftp_put是否不通过sftp连接触发?

我的代码用来写文件:

//Send file via sftp to server

$strServer = "*****";
$strServerPort = "****";
$strServerUsername = "*****";
$strServerPassword = "*****";
$csv_filename = "Test_File.csv";

//connect to server
$resConnection = ssh2_connect($strServer, $strServerPort);

if(ssh2_auth_password($resConnection, $strServerUsername, $strServerPassword)){
    //Initialize SFTP subsystem

    echo "connected";
    $resSFTP = ssh2_sftp($resConnection);

    $resFile = fopen("ssh2.sftp://{$resSFTP}/".$csv_filename, 'w');
    fwrite($resFile, "Testing");
    fclose($resFile);

}else{
    echo "Unable to authenticate on server";
}

有没有人成功抓取本地文件并通过上述方法使用sftp上传?一个例子将不胜感激。

谢谢


阅读 987

收藏
2020-05-29

共1个答案

小编典典

通过上述方法(涉及sftp),您可以使用stream_copy_to_stream

$resFile = fopen("ssh2.sftp://{$resSFTP}/".$csv_filename, 'w');
$srcFile = fopen("/home/myusername/".$csv_filename, 'r');
$writtenBytes = stream_copy_to_stream($srcFile, $resFile);
fclose($resFile);
fclose($srcFile);

您也可以尝试使用ssh2_scp_send

2020-05-29