Detecting AJAX requests with PHP.

This is a guide on how to detect AJAX requests with PHP. Please note that there is NO sure-fire way to detect AJAX requests on the server, as the headers involved can easily be spoofed by the client that is making the request. i.e. Do NOT rely on this for security.

In the vast majority of cases, Javascript frameworks and libraries such as JQuery will automatically add the X-Requested-With header to their HTTP requests. If you use Chrome Developer tools to inspect the AJAX requests that they send, you will find that they set the X-Requested-With header to “XMLHttpRequest“:

This means that you can detect AJAX requests with PHP by checking the HTTP_X_REQUESTED_WITH value in the $_SERVER superglobals array.

Here is a PHP code sample:

Pretty simple, right?

As I said above, this header cannot be trusted, as the client can easily set this value to anything that it wants to.

Spoofing AJAX requests with PHP.

Let’s take a look at how easy it is to fake / simulate an AJAX request using cURL and PHP:

See how easy that was? All I had to do was set the “X-Requested-With” header to “XMLHttpRequest” using the CURLOPT_HTTPHEADER option. If I really need to, I could also spoof the referrer field or modify the User Agent so that the server is fooled into thinking that my simulated XHR request came from a browser.

So be warned! Do not use this type of check for security purposes.

Facebook Comments