0

Why we use

header('Content-Type: application/json');

Before

echo  json_encode($data)

in the web services in php

If I will not use header('Content-Type: application/json'); what is its disadvantage?

Help will be appreciated

Ali Mehdi
  • 770
  • 1
  • 8
  • 28
  • 2
    Possible duplicate of [What is the correct JSON content type?](http://stackoverflow.com/questions/477816/what-is-the-correct-json-content-type) – Leo Jan 26 '16 at 14:00
  • How this is same? I am not asking that what is correct json type. I am asking if we don't use content-type than it will also work in web service. Also advantages of using it – Ali Mehdi Jan 26 '16 at 14:04
  • Ali it is not the same question but the answer there seems to suit your question – Leo Jan 26 '16 at 14:06
  • 1
    The disadvantage is that whatever calls your service will be misled and potentially misinterpret the returned value if I believes that it's getting the default "text/html". – Mark Baker Jan 26 '16 at 14:13
  • 1
    Because the content type header should match the content type of the response. If you dont set the header, php by default will send a content type header of `text/html` : http://php.net/manual/en/ini.core.php#ini.default-mimetype which could cause the client code to barf. Said client code **might** handle the mismatch, but just because it does is no reason to write bad code - you can write really crap html and most browsers will render it, but that doesnt mean you should! – Steve Jan 26 '16 at 14:14

2 Answers2

3

You should always set Content-Type: application/json if you are sending json. Headers are used to tell the other side what kind of data you are sending and is a best practice.

Blake A. Nichols
  • 832
  • 1
  • 6
  • 10
3

When you are defining the Content-Type in headers of the any response, tell the client about which type of content they are receiving in response. When we are sending the JSON encode string in the response we should always set Content-Type:application/json in headers.

Default "Content-Type:text/html" is set in response PHP headers.

Vikash Kumar
  • 981
  • 8
  • 15