如果我在代码中意外出错,使用PHP是否可以显示500页?我尝试使用error_reporting(0)
,但这只会隐藏错误。如果我使用htaccess的php_flag display_errors off
Chrome(和其他浏览器),只会显示一个500错误,如下所示:http://image.prntscr.com/image/4c87df1998634097a18a85d268ccc818.png
感谢:)
在PHP 5.x中,您可以捕获除致命错误之外的所有错误。只要看看http://php.net/manual/en/function.set-error-handler.php
快速示例:
<?php
function handler($errno, $errstr, $errfile, $errline)
{
echo file_get_contents('500.html');
die();
}
set_error_handler('handler', E_ALL);
组合这些函数以在出现错误时进行重定向:
error_get_last()
#获取最后一个错误
header()
#在需要时重新检查
register_shutdown_function()
#用error_get_last 捕获错误
ob_start() / ob_flush()
#捕获内容,用于延迟显示或不显示
在php文件的开头:
ob_start();
register_shutdown_function(function(){
$err = error_get_last();
//check the $err
if($err){
header('Location: 505.html');
exit;
} else {
ob_flush();#or ob_end_flush();
exit;
}
});
您还可以通过此捕获致命错误。
任何Web服务器(apache/nginx/lighttpd)都允许您执行自定义错误页面
https://httpd.apache.org/docs/2.4/custom-error.html
https://www.digitalocean.com/community/tutorials/how-to-configure-nginx-to-use-custom-error-pages-on-ubuntu-14-04
http://redmine.lighttpd.net/boards/2/topics/4639
但不要忘记关闭PHP错误显示,只需记录它们即可。