Reputation: 157927
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.
Upvotes: 6
Views: 3007
Reputation: 157828
Nowadays it's no more a problem - since 5.3 PHP learned at last to send 503 on error, not 200
Err, it seems it was 5.2.4:
Changed error handler to send HTTP 500 instead of blank page on PHP errors.
You need to set display_errors = off
to make it work
I have the exact behavior on my windows Apache 2.4 with PHP 5.4.5
Upvotes: 2
Reputation: 272006
Response headers are not sent until PHP echoes the first byte of response body. You can change headers (and the status code) in the mean time. Keeping that in mind, here is a solution:
Set your script to send a 500
response code at the beginning of 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 ensure that 200
response code is set at only one location in your code.
Note: you can use http_response_code
(PHP >= 5.4) instead of header
.
Upvotes: 2
Reputation: 146330
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.)
Upvotes: 2