Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm developing a PHP application that uses HTTP response codes for communication as well as response bodies. So this is a typical scenario in the PHP code:

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

... and the typical code in clients looks like:

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

This is cool, as long as every error is well caught in PHP code.

The problem: If, for any reason in the php code occures an uncaught error or an uncatchable error like syntax errors, Apache will send 200 OK. But I wan't apache to say 500 Internal Server Error. Maybe per .htaccess or so.

like image 587
hek2mgl Avatar asked Aug 05 '10 07:08

hek2mgl


People also ask

How is error handling done in PHP?

By default, PHP sends an error log to the server's logging system or a file, depending on how the error_log configuration is set in the php. ini file. By using the error_log() function you can send error logs to a specified file or a remote destination.

How do you get a specific error instead of an internal server error?

Another way of dealing with exceptions is to create your own error . html files. If you place a file in resources/static/error/500. html it should be returned when the Http-500 Internal Server Error is thrown.


1 Answers

You can, of course, write your own error handler. However, not all PHP errors are catchable. For instance, a syntax error won't even allow your code to run, including your error handler.

To handle catchable errors, you can use the auto_append_file and auto_prepend_file directives to place your error handling code code.

Non-catchable errors are a different issue. If PHP runs as Fast CGI, it will automatically generate a 500 status code for you. However, you're probably running PHP through some other SAPI (such as Apache module). No idea about that, sorry. (I'll report back if I find something.)

like image 103
Álvaro González Avatar answered Oct 11 '22 00:10

Álvaro González