Transfer file to remote server through SSH using PHP

0
8260
PHP Programming Language
PHP Programming Language

PHP is a really good scripting language to do some handy tasks, in this case, to transfer files to remote servers via SSH.

In order to issue SSH commands, you will need to config libssh2 and load php_ss2 extension to PHP config file.

The command used to transfer file is ssh2_scp_send. The usage is very simple, here is an example of using it:


$host = '127.0.0.1';
$username = 'petehouston';
$password = 'A_Secret_PassWord$2017';

$local_file = 'C:/package.zip';
$remote_file = '/home/petehouston/uploads/package.zip';

$connection = ssh2_connect($host, 22);

ssh2_auth_password($connection, $username, $password);

echo 'Uploading...'."\n";

$result = ssh2_scp_send($connection, $local_file, $remote_file, 0644);

if(!$result) {
    echo 'Error while uploading';
    exit(-1);
}

echo 'Uploaded successfully!'."\n";

The first parameter is the SSH connection instance generated by using ssh2_connect. After creating connection successfully, pass into ssh2_scp_send

This way, you can write custom script to automate file uploading to any server.