Detecting AJAX calls in PHP

AJAX, or asynchronous page loading is a great way of improving the user experience on your site. No matter how fast the network is between your server and your users’ devices, there is always some lag in page loading times and every tenth of a second matters. With AJAX, you load only the relevant content and your site can approach the performance of desktop applications. This will also greatly reduce your traffic usage and server load.

However, not everyone can ┬ábenefit from AJAX and if you follow the Progressive enhancements strategy (as you should) you will want to be able to tell the difference between request made through AJAX and the ‘regular’ ones. The easiest way to achieve so is this:

1
2
3
4
5
6
if( isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
    //AJAX call
}
else{
    //non-AJAX (regular) call
}

It is that simple. Strictly speaking it is not necessary to use isset() first, but you will get PHP Notice error if $_SERVER[‘HTTP_X_REQUESTED_WITH’] is not set.

Note that whatever detection method you use, hackers will always be able to spoof the requests, so don’t assume that calls made through AJAX are any safer than the ‘regular’ ones.

Read More