PHP: Setting the Content-Type of a cURL request.

This is a guide on how to set the Content-Type header using PHP’s cURL extension.

In many cases, web services will require 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 the Content-Type header and then 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

Obviously, you would only set the Content-Type to application/json if you were sending JSON via cURL.

However, what if you wanted to send XML data instead?

//Setting it to text/xml instead.
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'Content-Type: text/xml'
));

As you can see, we simply replaced “application/json” with “text/xml” in the PHP script above.

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 an HTML form is submitted via the browser.

However, if the request is a GET request, then this header will not be set at all.

This means that 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.

This is because “CONTENT_TYPE” does not exist inside the $_SERVER array.

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.