Saturday 20 August 2011

Ajax Session Time Out Handling in PHP

Recently I stuck up with ajax time out issue .Yup, my webpage went weird once the session get expired, as a result i can see my login page appeared inside the result div tag.

But i want to identify the session status and it should redirect to login page.Now the following steps shed some light to tackle this ajax session timeout issue.


During Ajax request , using the browser like Firefox, the requested url can be visible through console which further can be run from the browser address bar. This can be prevent by PHP’s $_SERVER['HTTP_X_REQUESTED_WITH'] variable.

If your are using simple javascript no jQuery, Mootools or any other JavaScript API, set the ajax request header to

xmlHttp.open(“GET”,url,true); // After this set header as
xmlHttp.setRequestHeader(“X-Requested-With”, “XMLHttpRequest”);

With jQurey,Mootools no need to set this header.

With PHP set this code

define(‘IS_AJAX’, isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == ‘xmlhttprequest’);

Now in ajax call page set the code as

if(!IS_AJAX){
echo ‘ Direct Access Is not Allowed’;
exit;

}

No comments:

Post a Comment