Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

php - Uploading files with 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";
}

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.

Thanks

question from:https://stackoverflow.com/questions/9572314/uploading-files-with-sftp

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

You can also try using ssh2_scp_send


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...