How to let Apache send 500 in case of PHP error?

I am developing a PHP application that uses HTTP response codes for communication as well as the response body. So this is a typical script in PHP code:

try { doSomething(); } catch (Exception $e) { header('HTTP/1.1 500 Internal Server Error'); } 

... and typical client code looks like this:

 switch(responseCode) { case 200 : // all fine // .... case 500 : // trouble! } 

This is cool if all errors are well caught in the PHP code.

Problem. If for some reason a fuzzy error or an elusive error, such as syntax errors , occurs in php code, Apache will send 200 OK. But I will not talk about the 500 Internal Server Error. Maybe for .htaccess or so.

+7
php apache error-handling
source share
3 answers

You can, of course, write your own error handler . However, not all PHP errors are fun. For example, a syntax error will not even let you run your code, including an error handler.

To handle exciting errors, you can use auto_append_file and auto_prepend_file to put error handling code.

Fatal errors are another problem. If PHP works like Fast CGI , it will automatically generate a 500 status code for you. However, you are probably using PHP through some other SAPI (such as the Apache module). I don’t know, sorry. (I will report if I find anything.)

+2
source share

Response headers are not sent until PHP repeats the first byte of the response body. You can change the headers (and status code) at an average time. Keeping this in mind, here is the solution:

Install a script to send a response code of 500 at the beginning of the script and 200 at the end. Here is an example:

 header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error'); if (rand(0, 1) == 1) { die("Script terminated prematurely"); } header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK'); echo "Success"; 

Just make sure that the 200 response code is installed in only one place in your code.

Note: you can use http_response_code (PHP> = 5.4) instead of header .

+2
source share

This is no longer a problem at the moment, since 5.3 PHP finally learned to send 503 to error, not 200

Err, it looks like it was 5.2.4 :

The error handler for sending HTTP 500 has been changed instead of a blank page for PHP errors.

You need to set display_errors = off for it to work

I have exact behavior on my Apache 2.4 windows with PHP 5.4.5

+2
source share

All Articles