Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP SFTP/SSH transfer

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

like image 568
Daniel H Avatar asked Dec 16 '25 20:12

Daniel H


2 Answers

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");
like image 196
Antonio Haley Avatar answered Dec 19 '25 11:12

Antonio Haley


As is too often the case here, you've not provided much information about what you are trying to achieve nor the constraints.

Where does the image originate from? How quickly does it need to be replicated? Are the servers equivalent nodes in a cluster?

Since both servers are already talking HTTP, why use a different protocol for transferring content?

As Antonio suggests you could simply exec scp - but this is only going to work if you've got key pairs set up.

A more flexible solution (assuming ssh is a requirement) would be to use the ssh bindings in PHP

like image 26
symcbean Avatar answered Dec 19 '25 12:12

symcbean



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!