PHP: Set custom headers with cURL.

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:

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:

Custom Headers Curl

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.

Pretty simple!

Facebook Comments