Execute a PHP file on Remote Server Using SSH

By: Sunil Kumar |  In: Server  |  Last Updated: 2017/10/30

When you are working on two different servers, sometimes you need to communicate from one server to other server using php file OR in simple words you need to execute a php file on other server staying on a local or another server.

Doing so is not a difficult task. you can do it easily following these steps

1. Installing php-ssh2

You need to install php-ssh2 library which provides access to resources (shell, remote exec, tunnelling, file transfer) on a remote machine using a secure cryptographic transport.

to install it –

 $ sudo apt-get update
 $ sudo apt-get install php-ssh2

2. Executing file on Remote Server

Now your server is ready to execute a file on any other server.

create a .php file on your current server like this-

&lt?php
/*server.php*/
$connection_string = ssh2_connect(address_to_server, 22);

// $connection_string = ssh2_connect('127.0.0.1', 22);

if (@ssh2_auth_password($connection_string, 'user', 'password'))
{
	echo "Authentication Successful!\n";
}
else
{
	throw new Exception("Authentication failed!");
}

$stream = ssh2_exec($connection_string, 'php /path to your php file');
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
echo stream_get_contents($stream_out);

and save this file.

now execute this file as

$ php server.php

If it output Authentication Successful! You are ready to execute further.

Comments


Leave a Comment

Your email address will not be published.

*


Sunil Kumar


I am the owner of acmeextension. I am a passionate writter and reader. I like writting technical stuff and simplifying complex stuff.
Know More

Subscribe to our mailing list


%d bloggers like this: