2

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.

Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453

1 Answers1

4

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.

a sad dude
  • 2,775
  • 17
  • 20
  • Be careful of `maximum_execution_time` and other resource limits set in php.ini. – ghoti Dec 21 '11 at 02:04
  • 2
    You're close, but you need to capture the output (/dev/null) from the script and make sure the script doesn't die (nohup) when the process that launched it ends. exec('nohup php /absolute/path/to/your/script.php >/dev/null &') – Brent Baisley Dec 21 '11 at 02:52
  • Thanks, forgot about nohup, edited. Also, I'm not sure in which situation exec, shell_exec or system should be used (and what is the difference, except for the return value), but shell_exec always works for me, so I recommend that. – a sad dude Dec 21 '11 at 15:21