Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a PHP script continue running after ending the HTTP request?

How do I write a PHP script that continues running, even after flushing out some text and ending the HTTP request? Is this possible?

like image 336
Robin Rodricks Avatar asked Sep 15 '09 16:09

Robin Rodricks


People also ask

Can a PHP script run forever?

You can make it run forever by either setting the value or call set_time_limit in your script (http://php.net/manual/en/function.set-time-limit.php).

Does PHP run in browser or server?

Chapter 1. PHP: What, Why, and Where? PHP is ultimately just text that is taken by your web server and turned into a set of commands and information for your web browser. And because you're just working in text, there's not a lot you have to do to get going as a PHP programmer.


2 Answers

To run PHP app forever or until php terminates

ignore_user_abort(true);

set_time_limit(0);
like image 68
ToughPal Avatar answered Oct 13 '22 06:10

ToughPal


You might be interested by the ignore_user_abort configuration directive, and/or the ignore_user_abort function :

Sets whether a client disconnect should cause a script to be aborted.

Using this, you could :

  • generate the part of the page that has to be sent to the browser
  • flush the output, with flush and/or ob_flush
  • call ignore_user_abort (either now or before)
  • do some more work

The user's browser will probably still indicate "waiting" or "loading", but the content of the page will be loaded and displayed -- and even if the user presses "stop", your script should continue its execution.

For more informations, there is an example on the manual's page of that function -- and you can take a look at this article : How to Use ignore_user_abort() to Do Processing Out of Band


Of course, while this can be used for some light process (like "cleaning up" stuff at the end of a page, while displaying it as fast as possible to the user), you'll still be limited by max_execution_time and the like.

So, this is not a solution that should be used for long/heavy calculations.

like image 30
Pascal MARTIN Avatar answered Oct 13 '22 05:10

Pascal MARTIN