This is a guide on how to set the Content-Type header using PHP’s cURL extension. In many cases, web services will require that you to set the Content-Type header before you send them a HTTP request.
Let’s jump right in and take a look at an example.
Using CURLOPT_HTTPHEADER to set the Content-Type header.
The great thing about cURL is that it allows you to set custom headers. As a result, we can simply create a Content-Type header and attach it to our request:
//The URL that you will be sending this //cURL request to. $url = 'http://localhost/test/log.php'; //Initiate and create a cURL resource. $curl = curl_init($url); //Use the CURLOPT_HTTPHEADER option to set the Content-Type //for the request. curl_setopt($curl, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json' )); /** * Set other cURL options here. */ //Setting request type to POST curl_setopt($curl, CURLOPT_POST, true); //Execute the request curl_exec($curl);
In the POST request above, we set the Content-Type header to “application/json”. We were able to do this by passing an array into cURL’s CURLOPT_HTTPHEADER option on line 10.
In my log.php file, I used the following piece of code to print out the received content type:
//Print out the received Content-Type header echo 'The Content-Type of this request was: ' . $_SERVER['CONTENT_TYPE'];
As a result, the following output was returned:
The Content-Type of this request was: application/json
//Setting it to text/xml instead. curl_setopt($curl, CURLOPT_HTTPHEADER, array( 'Content-Type: text/xml' ));
In the PHP snippet above, we simply substituted “application/json” with “text/xml”.
Default Content-Type of a cURL request.
By default, cURL will attach “application/x-www-form-urlencoded” as the type during a POST request. This is the Content-Type that is typically used whenever a HTML form is submitted via the browser. However, if the request is a GET request, then this header will not be set at all. i.e. The field will not exist.
For example: If you send a GET request to our custom PHP script and omit the custom header option, you will find that it spits out an undefined index error.
It’s not working?
If your script is not setting the header correctly, then there are probably other issues at play. To debug the problem, make sure that you use some basic cURL error handling.
Hopefully, you found this guide useful! Good luck!