Set response code for compile errors in PHP

66 Views Asked by At

PHP version 7.2

I would like the php endpoint to return a code 500 if the script fails to parse. Currently I get a code 200 with the response body:

<br/>
<b>Parse error</b>
:  syntax error, unexpected 'felkdfle' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST) in <b>/var/www/html/api/logs.php</b>
on line <b>9</b>
<br/>

The front end will not handle this as an error because the response says its a success.

I tried this:

// does not work because parse errors can not be caught within the script
function exception_handler(Throwable $exception) {
    http_response_code(500);
    echo "Uncaught exception: " , $exception->getMessage(), "\n";
}
set_exception_handler('exception_handler');

// also does not work
function fatal_handler() {
    http_response_code(500);
    $error = error_get_last();
    echo $error;
}
register_shutdown_function('fatal_handler');

So how can I set the response code php uses to respond after a parse error?

1

There are 1 best solutions below

15
stimulate On

This is a bug in PHP version 7.2, which we are using. I verified it on my local machine, the new version 8.4 returns 500 but the old version 7.2 returns 200

Edit: Bug may be overdramatic, it seems like a different default configuration. Apparently 7.2 uses display_errors = on by default (at least it behaves that way by default) and 8.3 has them off. Thats why 7.2 sends a 200 code when it logs the error to the browser. With an ini file setting display_errors = off it also returns the expected 500.