In a previous guide, we 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, we are 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:
//The URL of the script that receives //the AJAX request. $url = 'script.php'; //Create a cURL handle $curl = curl_init($url); //To fake or spoof an Ajax request, we will //manually set the X-Requested-With: XMLHttpRequest header curl_setopt($curl, CURLOPT_HTTPHEADER, array( 'X-Requested-With: XMLHttpRequest' )); //Tell cURL to return the transfer curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); //Execute our "fake" Ajax request. $output = curl_exec($curl); //Print the returned response echo $output;
In the code above, we:
- Created a cURL handle for the URL that receives the AJAX request.
- After that, we spoofed the X-Requested-With header by setting a custom header.
- We told cURL to return the output as a string instead of just dumping it out onto the page.
- 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 a header, then the client can change it.
That is the nature of HTTP requests.
Other related PHP guides.
- Spoofing MIME types with cURL and PHP.
- Spoofing the Referrer field using PHP.
- How to spoof a User Agent using PHP.