This article will show you how to add custom headers to a cURL HTTP request in PHP.
cURL is a popular tool for making HTTP requests, and is often used for testing APIs. Adding custom headers to a cURL request can be helpful for making authenticated requests or passing data that isn’t supported by the default cURL request headers.
Add headers to the cURL request
Adding custom headers to a cURL HTTP request in PHP can be done by using the
curl_setopt function. Let’s check the code below to understand it properly.
<?php //initiate the cURL $curl = curl_init(); curl_setopt ($curl, CURLOPT_URL, "https://codehasbug.com"); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt ($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //store custom header value in an array $header = array( 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Encoding: gzip,deflate', 'Accept-Language: en-US,en;q=0.5', 'Cache-Control: no-cache', 'Content-Type: application/x-www-form-urlencoded; charset=utf-8', 'referer: https://www.google.com/', 'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/22.214.171.124 Safari/537.36' ); //set custom header to the cURL request curl_setopt($curl, CURLOPT_HTTPHEADER, $header); curl_setopt($curl, CURLOPT_ENCODING, ''); $response = curl_exec($curl); curl_close($curl); echo $response; ?>
The CURLOPT_HTTPHEADER option sets an array of HTTP headers to be used in a cURL request. By using this technique, you can also set the authorization header to the cURL request.
I think the above methods will help you to add custom headers to a cURL HTTP request. That’s all for today’s tutorial. You can also learn something new in PHP from our PHP Tutorial. If you have any questions please comment below.