How to start a PHP background process on server side when user fetches a page?

I have no experience with PHP and I am wondering if this is possible:

I want to start a background PHP process when a user fetches a page. This process would check whether some delay has expired (for example a timestamp in a file) and execute accordingly. The page can 'return' before the process has finished its execution.

Is this realistic and if yes, how should I proceed? What would be the code to launch the process when the page is fetched? Thanks.

Upvotes: 2

Views: 4233

Answers (1)

a sad dude
a sad dude

Reputation: 2825

It is possible if your php is not limited for safety (and you have a CLI version of PHP installed too). Just run a new php process:

shell_exec('nohup php /absolute/path/to/your/script.php > /dev/null &');

Note the &. That will cause the process to run in the background. You can replace /dev/null with a filename to log the output. Also, if "php" doesn't work, try /usr/bin/php or php-cli.

Alternatively, you can just make an Ajax request from user's browser when the page loads. That request can take as long as needed (granted that the web server is configured properly) and will be completely invisible to the user.

Upvotes: 4

Related Questions