How to spoof an AJAX request using PHP.

In a previous guide, I wrote about how there is no way to tell if an HTTP request came via AJAX or not. This is because the X-Requested-With header can be easily spoofed. In this guide, I am going to show you how to fake or spoof an AJAX request using PHP’s cURL extension.

Take a look at the following cURL request:

In the code above, we:

  1. Created a cURL handle to the URL that receives the AJAX request.
  2. After that, we spoofed the X-Requested-With header by setting a custom header.
  3. We told cURL to return the output as a string instead of just dumping it out onto the page.
  4. Finally, we executed the HTTP request and printed out the result.

As you can see, in just a few lines of code, we were able to fake an AJAX request using PHP. This shows that you can never rely on HTTP headers such as X-Requested-With. If the client can send the header, then the client can change it. That is the nature of HTTP requests.

Other related PHP guides.

Facebook Comments