PHP

Use PHP To Detect An Ajax Request

Here is a quick PHP snippet that you can use to tell if the request coming to the page is from a form or from an Ajax request.

Where a page is being accessed by AJAX it will post data using XML, PHP can then pick up on the HTTP request and see what the return is expecting. For this you just need to use the PHP server variable and grab the parameter HTTP_X_Requested_With.

$_SERVER['HTTP_X_REQUESTED_WITH']

This would be useful to use on your page to block it being accessed via an AJAX request for this use the following example.

if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{

exit;

}

continue;

This is check is the HTTP_X_REQUESTED_WITH parameter is not empty and if it's equal to xmlhttprequest, it this matches then it will exit from the script.

Back to top