Reputation: 733
First of all Im using PHP 5.4.3.
The problem I have is that whenever an error occurs in a PHP file (such as parse error), it will display an error message in HTML and the HTTP status of the page will be 200.
What I want to know is how can I set the HTTP status to 500 if any errors occur and to display no errors at all.
Keep in mind that I do not want to display HTTP status 500 for every page, only for a few.
Upvotes: 6
Views: 2273
Reputation: 2921
You can use register shutdown function. Source: PHP : Custom error handler - handling parse & fatal errors
ini_set('display_errors', 0);
function shutdown() {
if (!is_null(error_get_last())) {
http_response_code(500);
}
}
register_shutdown_function('shutdown');
Note, E_PARSE errors will only be caught in files that are included/required after the shutdown function is registered.
Upvotes: 2
Reputation: 48357
myninjaname's answer is nearly right - however you don't know what's happened with the output buffer at exit. Also, your code will always run to completion. I'd go with using output buffering and a custom error_handler in addition to handling the situation immediately, guaranteeing the response to the browser this also makes it easier to trap and log information relevant to the error so you can fix any bugs:
<?php
ob_start();
set_error_handler('whoops');
function whoops($errno, $errstr, $errfile, $errline, $errcontext)
{
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
$logged="$errno: $errstr\nin $errfile at $errline\n";
foreach($errcontext as $scoped=>$val) {
$logged.=" $scoped = $val\n";
}
$logged.="Output = " . ob_get_clean() . "\n";
// NB still buffering...
debug_print_backtrace();
$logged.="stack trace = " . ob_get_clean() . "\n";
print "whoops";
ob_end_flush();
write_log_file($logged);
exit;
}
You can really handle parse errors - they occur when you've written and deployed bad code - you should know how to prevent this happening on a production system. Adding more code to try to solve the problem is an oxymoron.
You should also disable displaying of errors (not reporting) by setting display_errors=0 in your ini file.
update
I tried to catch any errors that occur with a custom error handler, but for some reason people say that it doesn't catch parse errors (and a few others too).
Don't you know how to test this for yourself? IIRC a lot depends on the context (a shutdown function can catch some parse errors in included content) and the version of PHP. But as above, if you have got to the point where such an error occurs on a production system, it's because you've failed to do your job properly.
Upvotes: 1
Reputation: 219794
error_reporting(0)
;header("HTTP/1.0 500 Internal Server Error");
Reference
Upvotes: 0