This is a guide on how to set custom request headers with PHP’s cuRL extension. Using cURL’s CURLOPT_HTTPHEADER option, we can change request headers such as Referer, Cookie, User-Agent and Accept-Encoding.
Take a look at the following cURL request:
//The URL you're sending the request to.
$url = 'http://localhost/test/file.php';
//Create a cURL handle.
$ch = curl_init($url);
//Create an array of custom headers.
$customHeaders = array(
'Accept-Encoding: gzip, deflate, br',
//Use the CURLOPT_HTTPHEADER option to use our
curl_setopt($ch, CURLOPT_HTTPHEADER, $customHeaders);
//Set options to follow redirects and return output
//as a string.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
//Execute the request.
$result = curl_exec($ch);
In the PHP code above, we are sending a GET request to a localhost URL. We also created a PHP array called $customHeaders, which will contain the custom headers that we want to send.
In this case, I set three custom headers using the CURLOPT_HTTPHEADER option:
- I set the Accept-Encoding header to gzip, deflate and br (Brotli).
- I provided a PHPSESSID value as the Cookie header.
- The HTTP referer header is set to the Google search engine. This is called referrer spoofing.
If you send the cURL request above to a PHP script that prints out the $_SERVER array, you should see something like the following:
In the screenshot above, you can see that my custom request headers have been received by the script:
- The contents of Accept-Encoding were parsed as HTTP_ACCEPT_ENCODING.
- Cookie was parsed as HTTP_COOKIE.
- Referer was parsed as HTTP_REFERER.