Home > Back-end >  php header printing full html code on browser
php header printing full html code on browser

Time:12-13

I am making a simple API from PHP.

Code Snippet:

        elseif ($_GET["command"]="verifyconn"){
            header("Content-Type: application/json");
            $data=array("response" => "success");
            echo json_encode($data);
            exit;
        }

Whenever this is executed, I get this response on browser:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>

<body>
</body>
</html>{"response":"wrong_secret"}

The whole HTML code gets printed on browser. When I remove header("Content-Type: application/json");, it gets fixed and JSON displays but in text. How can I fix it?

CodePudding user response:

It doesn't get really fixed when you remove the content type header, but the HTML part will become "invisible", because the content type will fall back to the default text/html; if you check the source code of the page, you will see it's still there.

The real solution is to search for where the above HTML is printed and remove it.

  • Related