0

In php-fpm(5.6) on nginx(1.20.1), I'm making an API that responds with http status code 500, some headers and body of json type.

header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header("Access-Control-Allow-Credentials: true");
header("Content-Type: application/json");

http_response_code(500);
die(json_encode([
  'errorMsg' => 'Something went wrong',
]));

But it seems the server responds without the headers and the body as clients(at least Chrome browser) don't receive them.

I tried setting a http status lower than 500 like 40x, and it made the server respond with the headers and the body as I expected.

Do other servers/applications also omit headers and body in response with http status 50x? Or it's just a problem specific to either php or nginx?

Changdae Park
  • 911
  • 1
  • 9
  • 22
  • 1
    Usually, 5xx errors are generated by server faults, they don't return any content. If something is wrong with the request, 4xx are dedicated (not authorized, no content, I'm a teapot ^^). But this answer : https://stackoverflow.com/a/73917133/4698373 may interest you. – Philippe May 24 '23 at 10:43

1 Answers1

0

Your code works if you comment the first line, which generates an error, with the consequence that no header can be sent after output.

<?
//header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header("Access-Control-Allow-Credentials: true");
header("Content-Type: application/json");

http_response_code(500);
die(json_encode([
  'errorMsg' => 'Something went wrong',
]));
?>

Of course, in the response there is no Access-Control-Allow-Origin, but we can see : headers

and the correct output: ouput

On my tests platform (php 8.11), $_SERVER['HTTP_ORIGIN'] generates the following error :

Warning: Undefined array key "HTTP_ORIGIN"

Please have a look at this answer to understand why.

Of course, if I set ini_set('display_errors','Off') as first line, all seems working fine but no Access-Control-Allow-Origin header is more present.

Philippe
  • 1,134
  • 12
  • 22
  • I know that depending on the user agent, `$_SERVER['HTTP_ORIGIN']` can be undefined. But my test bed is where it's always defined. And I'm requesting to a different origin, so I need to allow CORS by `Access-Control-Allow-Origin` header. – Changdae Park Jun 01 '23 at 09:30
  • Hum, did you try to set it via [nginx configuration](https://serverfault.com/a/176729/987415) instead of via PHP? @ChangdaePark – Philippe Jun 01 '23 at 09:41
  • Do you mean you can respond with body via nginx configuration even when it's 50x? – Changdae Park Jun 01 '23 at 13:05