views:

704

answers:

5

PHP scripts can continue executing after the HTTP page request, so how do I finally stop it executing when I'm done with it?

Also, is there an event to detect when the OS is going to forcibly abort the script? or how do I keep an internal timer to predict max_execution_time?

+5  A: 

exit()/die() will stop a php script.

To know when to stop the script, you'll just have to use microtime as a timer and save as a constant (or fetch from the php.ini file) the maximum execution time.

You can also look at the Connection handling information. Where we have things like connection_aborted() and connection_status()

But what is the problem you're trying to solve?

Ólafur Waage
+1  A: 

Well, you could start a $start=microtime(true) which will return a timestamp. Then you can just keep checking microtime(true) and subtract that from your start time to get the number of seconds since executing.

But no, you can't "catch" the script as its terminating for the reason of the request being too long. You could try to do some last minute stuff in the shutdown handler, but I'm not sure if PHP will honor that.

It looks like there used to be a function that does exactly what you want, connection_timeout(), but it was deprecated and removed. Don't know if there is any kind of replacement for this, however.

ryeguy
+1  A: 

You may want to take a look at pcntl-alarm which allows a script to send a signal to itself. Also contains some sample on how to catch the kill signals which can be send by the OS. And die() indeed.

Ticcie
+3  A: 

You can use register_shutdown_function to register a function to be called at the end of script execution. You can use this to detect when the script has been terminated and perform a certain set of actions.

tj111
+3  A: 

To have a callback at the moment your request is shutting down, use register_shutdown_function( myfunction ).

Much like most POSIX environments, PHP also supports signal handlers. You can register your own handler for the SIGTERM event.

function my_abort_handler( $signo ) {
   echo "Aborted";
}

pcntl_signal( SIGTERM, "my_abort_handler" );
xtofl