Home > Mobile >  Slim framework does not send http headers when http status is not 200
Slim framework does not send http headers when http status is not 200

Time:10-31

I am using the PHP Slim framework v4. I try to send an HTTP header and an HTTP error code. With HTTP status 200 it is working fine. When specifying 304, the response error code is fine, but the headers are missing in this case.

return $response->withHeader('Content-Type', 'text/plain')
    ->withHeader('X-Error-Message', $message)
    ->withHeader("Access-Control-Allow-Origin", $_SERVER['HTTP_ORIGIN'])
    ->withStatus(200);

This works, but the code as stated below does not submit the headers

return $response->withHeader('Content-Type', 'text/plain')
    ->withHeader('X-Error-Message', $message)
    ->withHeader("Access-Control-Allow-Origin", $_SERVER['HTTP_ORIGIN'])
    ->withStatus(304);

Any ideas why this isn't working?

As you see, I need a CORS header to avoid that the browsers throws an error.

CodePudding user response:

I guess you get this internal warning in PHP:

Warning: Undefined array key "HTTP_ORIGIN" 

This warning will be sent by PHP before the Slim $response is getting handled.

Please note that the HTTP_ORIGIN header is not always present, and it is not good practice to rely on this key. Instead it's better to check the domain and send a * when it's valid.

This prevent this warning try this:

$httpOrigin = $request->getServerParams()['HTTP_ORIGIN'] ?? '';
if($httpOrigin) {
    $response = $response->withHeader('Access-Control-Allow-Origin', $httpOrigin);
}

return  $response->withHeader('Content-Type', 'text/plain')
    ->withHeader('X-Error-Message', $message)
    ->withStatus(403);

CodePudding user response:

The issue as reported in not caused by the slim framework. Our hosting provider is using apache as web server. Apache is causing this behaviour.

See https://bz.apache.org/bugzilla/show_bug.cgi?id=61820 for more details.

  • Related