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 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:

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:

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?

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!

Facebook Comments