【问题标题】:Include 500 file if PHP errors are found如果发现 PHP 错误,则包含 500 文件
【发布时间】:2016-08-03 14:43:31
【问题描述】:

如果我在代码中意外出错,是否可以使用 PHP 显示 500 页?我尝试使用error_reporting(0),但这只会隐藏错误。如果我使用 htaccess' php_flag display_errors off Chrome(和其他浏览器)将只显示 500 错误,如下所示:http://image.prntscr.com/image/4c87df1998634097a18a85d268ccc818.png

谢谢:)

【问题讨论】:

  • 只是为了澄清一下:如果发生 500 错误,您想显示一个页面吗?
  • 一般规则:如果您收到 500 错误,您首先要检查服务器的错误日志以获取有关 500 的详细信息。
  • @Fairy 不,如果我的 PHP 代码出错,我想显示 500 页,这样用户就不会看到 PHP 警告。我知道我可以隐藏它们,但我更喜欢显示有用的 500 页面

标签: php .htaccess


【解决方案1】:

在 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);

【讨论】:

    【解决方案2】:

    组合这些函数以在错误时进行重定向:

    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;
       }
    });
    

    你也可以用这个捕获致命错误。

    【讨论】:

    • 谢谢!但它也能捕获解析错误吗?
    • parse errors 如果您的意思是 php 代码解析错误:不。编译是在执行之前,在编译时检查语法中的错误
    • php_check_syntax (string $filename [, string &$error_message ])
    【解决方案3】:

    任何网络服务器 (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 错误显示,只需记录它们。

    【讨论】:

      猜你喜欢
      • 2013-08-10
      • 2013-02-17
      • 2017-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-25
      • 2015-09-14
      相关资源
      最近更新 更多