In this guide, we will show you how to set custom request headers with PHP’s cuRL extension.
We can change header values pretty easily using the CURLOPT_HTTPHEADER option.
For example, we could modify the Referer, Cookie, User-Agent or Accept-Encoding headers.
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', 'Cookie: PHPSESSID=ciqas3vp82m514iubpr1b0md3o;', 'Referer: https://www.google.com/' ); //Use the CURLOPT_HTTPHEADER option to use our //custom headers. 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); echo $result;
In the PHP code above, we sent a GET request to a localhost URL.
We also created a PHP array called $customHeaders, which contains all of the custom headers that we want to send.
In this case, we set three custom headers using the CURLOPT_HTTPHEADER option:
- We set the “Accept-Encoding” header to gzip, deflate and br (Brotli).
- We provided a PHPSESSID value as the “Cookie” header.
- Finally, we set the HTTP referer to a Google search URL. This is called referrer spoofing.
If you send this cURL request to a PHP script that prints out the $_SERVER array, you will see something like this:
In the screenshot above, you can see that the script has received our headers:
- The “Accept-Encoding” header is HTTP_ACCEPT_ENCODING.
- Cookie is HTTP_COOKIE.
- Referer is HTTP_REFERER.
Pretty simple!