0

I am trying to return json data from a php script. The data is formatted as json and I am setting the header "Content-Type: application/json". This works fine until I put my header() call inside of an if($_SERVER['REQUEST_METHOD'] == 'GET'){ block

<?php

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
   header("Content-Type: application/json");
   echo '{"name":"Larry","town":"Pungaville"}';
}

The problem is that the Content-Type header falls back to text/html, perhaps indicating that there is some output happening before I call header(). - but where?

Now it gets weird, when I change the if-statement to (1==1). The header is set correctly as application/json. This is not simply a case of the 'if' failing as the data is still output either time.

<?php

if (1==1){
   header("Content-Type: application/json");
   echo '{"name":"Larry","town":"Pungaville"}';
}

What is happening? How can ($_SERVER['REQUEST_METHOD'] == 'GET') be causing output? There is nothing else inside the php files besides what is shown here. I am testing the returned headers with curl and viewing the payload in Firefox.

I am using php8.1 with nginx 1.18.0 on Ubuntu 22.04

64bitFrog
  • 36
  • 3
  • why not call `header("Content-Type: application/json");` at the start of the script if you wanna return json all the time? – Albert Logic Einstein Aug 13 '22 at 03:45
  • Check your log for a "Headers already sent" warning and fix the problem. See https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php – Barmar Aug 13 '22 at 04:16

0 Answers0