Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 684
naspy971 Avatar asked Jun 05 '17 21:06

naspy971


2 Answers

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).

like image 59
naspy971 Avatar answered Sep 22 '22 03:09

naspy971


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.

like image 45
SLaks Avatar answered Sep 20 '22 03:09

SLaks