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