PHP: Spoof HTTP referer field with cURL.

In this short PHP guide, I will show you how easy it is to spoof the HTTP referer field using cURL. In previous tutorials, I have pointed out how the HTTP_REFERER field cannot be trusted.

This is why.

In the code below, we send a simple GET request using m.facebook.com as the referer address:

<?php

//Initiate cURL.
$ch = curl_init();

//The URL cURL will be sending a request to.
curl_setopt($ch, CURLOPT_URL, 'http://test.com/');

//The referer we will give the website above.
curl_setopt($ch, CURLOPT_REFERER, 'https://m.facebook.com/');

//Follow any header redirects
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

//If there is a redirect, we want to keep the referral URL we
//set above.
curl_setopt($ch, CURLOPT_AUTOREFERER, true);

//Execute the cURL request.
$result = curl_exec($ch);

//Close the cURL handle.
curl_close($ch);

An explanation of the code above:

  1. We created a cURL handle by using the curl_init function.
  2. We set the target to test.com by setting theĀ CURLOPT_URL option.
  3. After that, we set the HTTP referer field to m.facebook.com. This means that the server will think that our request was a result of somebody clicking on a link on Facebook.
  4. We setĀ CURLOPT_FOLLOWLOCATION to true. This tells cURL that it should follow any redirects.
  5. We set CURLOPT_AUTOREFERER to true. As a result, cURL will “keep” our referer info if it does encounter a redirect.
  6. Finally, we execute the GET request and close the cURL handle.

If you were the owner of test.com and you printed the $_SERVER[‘HTTP_REFERER’] variable out on to the page, it would read “https://m.facebook.com/”

In conclusion: Do not trust the HTTP referer field.