Skip to content

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

Ayyaz Zafar1 min read

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

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 screenstream_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);

Latest tutorials

All 754 →

Get new tutorials by email

One email when something new is published. Unsubscribe anytime.

Written by Ayyaz Zafar, full-stack developer for 15+ years. Work with me