PHP: How to run / execute a script in the background forever through SSH ?

24/09/2024 — Ayyaz Zafar Uncategorized

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);
Share this post.
Stay up-to-date

Subscribe to our newsletter

Don't miss this

You might also like