Monday 3 September 2018

When to use the 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

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.

0 comments:

Post a Comment