Ignore User Aborts with PHP

by jeremyjones on March 8, 2011

When you are developing or supporting a website, it does not always work perfectly. Sometimes a visitor will abort a script that is running and when that happens you want to try and avoid that causing a client disconnect. The ignore_user_abort() function determines whether the remote client can abort the running of the script.
This example demonstrates how to use this function. Without an input it will return the setting in the ini file.

{code type=php}<?php
ignore_user_abort();
?>{/code}

This should then return the value 0.
If you use this function, then PHP will not know that the user has tried to abort the connection until there is an attempt to send information back to the client. The use of an echo statement will not guarantee that information is sent.
This next example is a complete demonstration of how the ignore_user_abort() function works:

{code type=php}
<?php
// Ignores user abort – the script can run forever
ignore_user_abort(true);
set_time_limit(0);

echo ‘Connection Handling Text’;

// Runs a loop
while(1)
{
// Checks if the connection failed
if(connection_status() != CONNECTION_NORMAL)
{
break;
}
// Pause 10 seconds
sleep(10);
}
// The visitor broke while in the loop
// Perform other tasks independent of the browser
?>
{/code}

Leave a Comment

Previous post:

Next post: