PHP: How to run / execute a script in the background forever through SSH ?
You can execute a php script in the background forever by using SSH through PHP but for that you have to make sure first that SSH2 extension is available.
PHP DOCS: http://www.php.net/manual/en/function.ssh2-exec.php
$connection = ssh2_connect('shell.example.com', 22); ssh2_auth_password($connection, 'username', 'password'); /* if you want to execute script from a different directory then use commands in same line separated by ';', that is required in php. In below second command '&' will do the magic to run command forever. */ $stream = ssh2_exec($connection, 'cd httpdocs/subdir/dir; /path/to/php server.php &'); $stream = ssh2_exec($connection, 'ps aux | grep server.php'); // printing ssh output on screen stream_set_blocking($stream, true); $stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO); echo stream_get_contents($stream_out); // closing ssh connection $stream = ssh2_exec($connection, 'exit'); unset($connection);
1$connection = ssh2_connect('shell.example.com', 22);
2ssh2_auth_password($connection, 'username', 'password');
3
4/* if you want to execute script from a different directory then use commands in same line separated
5 by ';', that is required in php.
6 In below second command '&' will do the magic to run command forever.
7*/
8$stream = ssh2_exec($connection, 'cd httpdocs/subdir/dir; /path/to/php server.php &');
9$stream = ssh2_exec($connection, 'ps aux | grep server.php');
10
11// printing ssh output on screen
12stream_set_blocking($stream, true);
13$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
14echo stream_get_contents($stream_out);
15// closing ssh connection
16$stream = ssh2_exec($connection, 'exit');
17unset($connection);
18