How to add custom headers to a cURL HTTP request in PHP?

This article will show you how to add custom headers to a cURL HTTP request in PHP.

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.

	//initiate the cURL
	$curl = curl_init();
	curl_setopt ($curl, CURLOPT_URL, "");
	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',
		'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/ 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);	

	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.

Final Words:

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.

About Ashis Biswas

A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.

Leave a Comment