使用SFTP上传文件 [英] Uploading files with SFTP
问题描述
我已经通过ftp成功上传了文件,但是现在我需要通过SFTP进行上传.我可以成功连接到远程服务器,创建文件并写入文件,但是无法将现有文件从本地服务器上载到远程服务器. ftp_put不能通过sftp连接触发吗?
I have successfully uploaded files over ftp, but I now need to do via SFTP. I can successfully connect to the remote server, create a file and write to it, but I am unable to upload an existing file from my local server to the remote server. Is ftp_put not firing with an sftp connection?
我用来编写文件的代码:
My code used to write a file :
//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这样的方法上载吗?一个例子将不胜感激.
Has anyone had any success in grabbing a local file and uploading via a method such as above with sftp? An example would be greatly appreciated.
谢谢
推荐答案
With the method above (involving sftp) you can use 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
这篇关于使用SFTP上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!