Posts Tagged ‘timeout’

Php:Connection Handling

Tuesday, July 1st, 2008

PHP maintains a connection status bitfield with 3 bits:
0 - NORMAL

1 - ABORTED

2 - TIMEOUT
By default a PHP script is terminated when the connection to the client is broken and the ABORTED
bit is turned on. This can be changed using the ignore_user_abort() function. The TIMEOUT bit is
set when the script timelimit is exceed. This timelimit can be set using set_time_limit().

<?php
set_time_limit(0);
ignore_user_abort(true);
/* code which will always run to completion */
?>
You can call connection_status() to check on the status of a connection.

<?php
ignore_user_abort(true);
echo “some output”;
if(connection_status()==0) {
// Code that only runs when the connection is still alive
} else {
// Code that only runs on an abort
}
?>
You can also register a function which will be called at the end of the script no matter how the script
was terminated.

<?php
function foo() {
if(connection_status() & 1)
error_log(”Connection Aborted”,0);
if(connection_status() & 2)
error_log(”Connection Timed Out”,0);
if(!connection_status())
error_log(”Normal Exit”,0);
}
register_shutdown_function(’foo’);
?>

Php:Cookie Expiry

Monday, June 30th, 2008

Problem
Short expiry cookies depend on users having their system clocks set correctly.

Solution
Don’t depend on the users having their clocks set right. Embed the timeout based on your server’s
clock in the cookie.

<?php
$value = time()+3600 . ‘:’ . $variable;
SetCookie(’Cookie_Name’,$value);
?>
Then when you receive the cookie, decode it and determine if it is still valid.

<?php
list($ts,$variable) = explode(’:',$Cookie_Name,2);
if($ts < time()) {

} else {
SetCookie(’Cookie_Name’,”);
}
?>