When to use header('Content-Type: application/json') in PHP

42,271

Solution 1

Ok for those who are interested, I finally figured out that header('Content-Type: application/json') is used when another page is calling the php script, so that the other page can automatically parse the result as json.

For instance i have in my test.php :

header('Content-type: application/json; charset=utf-8');
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr); // {"a":1,"b":2,"c":3,"d":4,"e":5}

and in my main.js

function test() {
    $.ajax({
        url: 'test.php',
        type: 'GET',
        //dataType: 'html',
        success: function (response) {
            alert(response);
        }
    });
};

When I dont have dataType set to "json" or when I don't have the header in my test.php, the alert gives {"a":1,"b":2,"c":3,"d":4,"e":5} which is a string (tried with typeof(response), and when I have this header, or dataType:"json", I get [object Object] from the alert. So this header function is there to indicate to the calling pages which type of data it gives back, so that you can know how to deal with it. In my script, if I didn't have header('Content-Type: application/json'), I would have to parse the response in the javascript like this : JSON.parse(response) in order to make it a json, but with that header, I already have a json object, and I can parse it to html with jSON.stringify(response).

Solution 2

You should always set the Content-Type for any HTTP response to describe what you're serving in that response.

Whether it's JSON or something else, and whether it's for an AJAX request or any other kind of request.


You should also set the Content-Type for any request to describe your POST payload.

Solution 3

In PHP, if you don't specify the Content-Type header in the script, it will default to whatever you've configured default-mimetype to be in your php.ini file which is usually text/html.

Calling header('Content-Type: application/json') will override that default setting so that the script will respond with that Content-Type when requested.

Also, when calling curl with a Content-type:application/json header, you're specifying the content type for your request body and not for the expected reponse.

Share:
42,271
naspy971
Author by

naspy971

Updated on January 28, 2020

Comments

  • naspy971
    naspy971 about 4 years

    I've been trying to figure out what's really the usage of header('Content-Type: application/json') in php scripts and I've found different questions and answers on stackoverflow about this subject but I still don't completely get it...

    So here's the question : I've seen in some php projects this line of code, and I'm trying to understand

    • if this is used when another web page is calling this actual script (with ajax for example) so that the calling page can get a json from the php page

    OR

    • if this script means that the php page is going to deal with json sent from another web page. Or maybe something else ???

    Another thing that could help me if answered, lately I've been retrieving json from a resource (external url) with cURL and I had to put this header (Content-type:application/json) in the request. Did I send this header to the exertnal resource or was this MY header so that I can deal with the returned json ?

    thanks

  • naspy971
    naspy971 almost 7 years
    So let's say I send json data to the php script with ajax, if I don't put this header in my php script, what will happen ?
  • Haidar Zeineddine
    Haidar Zeineddine almost 7 years
    The request will be sent successfully and the receiver should guess the type of the content you sent him.
  • naspy971
    naspy971 almost 7 years
    Ok and still for ajax, when I request with dataType: json, I must put this header in my phpscript so that the returned data represents a json object, right ?
  • Haidar Zeineddine
    Haidar Zeineddine almost 7 years
    Datatype in ajax is what you expect the type of the data to be returned.
  • naspy971
    naspy971 almost 7 years
    If i fully understand, having that header means that when a server request this php page, it will deal with json and not html text, right ?
  • Haidar Zeineddine
    Haidar Zeineddine almost 7 years
    That means when having the "Content-Type" header the type of data carried to the php page is JSON and the php page should know how to handle that. And if you informed that the "DataType" is JSON , the php page should know that the receiver prefers JSON responses over other types(i.e text/html).