4

I'm currently using the following php exec command to load a url on the server side as I need a solution that doesn't involve a cron job and that is also asynchronous i.e. the user can navigate away form the page once the task is initiated and the task will still execute:

exec("nohup curl ".$dbupdateurl." > /dev/null 2>&1 & echo $!");

This works fine most of the time however is rather unpredictable. Is there a better/more solid way to achieve this?

Thanks,

Matt

user1419810
  • 836
  • 1
  • 16
  • 29

1 Answers1

0

If you are using PHP-FPM, you can use fastcgi_finish_request:

This function flushes all response data to the client and finishes the request. This allows for time consuming tasks to be performed without leaving the connection to the client open.

This way you can use PHP's native functions to do your webrequest after the user has already gotten the response. An example on how to use this function can be found in example of how to use fastcgi_finish_request()

If you are not using PHP-FPM, you can use a JobQueue like Gearman to do work outside the original request. This is probably the most reliable way of doing it, as it's a dedicated system for handling these kinds of jobs.

Also note that curl can do async http requests. If the issue is that you dont want to wait for the http response, this might be an easier solution than introducing a JobQueue.

Last but not least, you can fork additional PHP process to do the work. See How can I do time consuming task after sending response to client and php execute a background process

Community
  • 1
  • 1
Gordon
  • 312,688
  • 75
  • 539
  • 559