PHP SFTP/SSH transfer

Daniel H picture Daniel H · Jun 22, 2011 · Viewed 8.3k times · Source

I posted a question a little while ago but I asked about FTP, which is the wrong question (doh!). I need to automatically transfer images (e.g. test.jpg) from one server to another using SFTP/SSH.

Could someone please explain how I would do this? I am completely new to this kind of thing so as much information as possible would be really appreciated.

Thanks for any help

<?php

$local_file = "http://localhost/ftptest/logo.png";
$remote_file = "/logo.png";

exec("scp $local_file username:pass@***.**.238.87:$remote_file");

?>

edit:

in the end I found that this works:

<?php

     include('Net/SFTP.php');

     $image = 'logo.jpg'; //image to be uploaded - needs to be in the same directory as this script e.g. just logo.jpg

     $image_contents = file_get_contents($image); // location of image to be uploaded

     $sftp = new Net_SFTP('***.**.**.**'); // server address to connect to
     if (!$sftp->login('***', '***')) { // server login details
         exit('Login Failed');
     }

     echo $sftp->pwd();
     $sftp->put($image, $image_contents); // upload a file $image with the image contents.

?>

Couldn't get the SSH working but hopefully this will help someone in the future :)

Answer

Antonio Haley picture Antonio Haley · Jun 22, 2011

A simple way to handle this is to call PHP exec and execute a unix scp call.

exec("scp $local_file user1@somehost:$remote_file");