PHP Connection Handling

From php.net:

Internally in PHP a connection status is maintained. There are 4 possible states:

  • 0 – NORMAL
  • 1 – ABORTED
  • 2 – TIMEOUT
  • 3 – ABORTED and TIMEOUT

If the PHP-imposed time limit (see set_time_limit()) is hit, the TIMEOUT state flag is turned on.

The default behavior is for your script to be aborted when the remote client disconnects. This behavior can be set via the ignore_user_abort php.ini directive as well as through the corresponding php_value ignore_user_abort Apache httpd.conf directive or with the ignore_user_abort() function.

Use register_shutdown_function():  With a shutdown function, when the remote user hits his STOP button, the next time your script tries to output something PHP will detect that the connection has been aborted and the shutdown function is called. This shutdown function will also get called at the end of your script terminating normally, so to do something different in case of a client disconnect you can use the connection_aborted() function. This function will return TRUE if the connection was aborted.

The default timeout is 30 seconds.  It can be changed using the max_execution_time php.ini directive or the corresponding php_value max_execution_timeApache httpd.conf directive as well as with the set_time_limit() function.   connection_status() function. This function will return 2 if a timeout caused the shutdown function to be called.

One thing to note is that both the ABORTED and the TIMEOUT states can be active at the same time. This is possible if you tell PHP to ignore user aborts. PHP will still note the fact that a user may have broken the connection, but the script will keep running. If it then hits the time limit it will be aborted and your shutdown function, if any, will be called. At this point you will find that connection_status() returns 3.

 

Bottom line, to finish the script no matter what,

ignore_user_abort(true);
set_time_limit(0);

Note: web server might catch you out with an imposed HTTP timeout (usually around 5 minutes).

Note on Shutdown Function:
If you want to do something with files in function, that registered in register_shutdown_function(), use ABSOLUTE paths to files instead of relative. Because when script processing is complete current working directory changes to ServerRoot (see httpd.conf)