gpt4 book ai didi

PHP自定义错误页面

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:36:52 26 4
gpt4 key购买 nike

每个人都说在事件站点中“允许显示错误”是不好的(由于一些安全问题)。

现在,我们必须考虑两种情况:

  1. 网站处于 Debug模式
  2. 该站点未处于 Debug模式

现在,对于案例 #1:

我们希望看到错误。怎么办?

ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);

没有比这更简单的了。我们还可以为除 Parse 和 Fatal 之外的所有错误自定义错误处理程序。

相反,如果情况是 #2:

我们希望能够停用消息:

ini_set('error_reporting', 0);
ini_set('display_errors', 0);

没关系。但是如何向用户显示一条友好的消息,例如“嘿,伙计,事情真的很糟糕。我不能向你保证我们正在努力修复它,因为我们很懒惰。”。您应该再次启用错误并仅使用函数 set_error_handler() 并希望不会发生解析或 fatal error 。但我的第一个问题是:

Question 1: Is that possible to avoid error reporting and have a custom offline page that is loaded when something goes wrong? I mean, is it possible to have ini_set('error_reporting', 0); and ini_set('display_errors', 0); and still be able to tell PHP to load a custom Error page?

现在是另一个:

Question 2: I developed a class that with the power of set_error_handler() logs errors occurred into the database. In this way I can keep track of hack attempts and other cool stuff. (And yes, i'm always sure the DB is accessible since my application shuts down if we cannot connect to the DB). Is this worth something?

最佳答案

前段时间我创建了一个小系统,当发生 fatal error /抛出未捕获的异常时,它会将您重定向到错误页面。假设每个请求都由一个文件处理并以该文件结束是可能的,因此通过到达该文件的末尾,我确信一切正常。在这种情况下,我已经设置了在错误页面上重定向的功能并将其注册为关闭功能 - 因此它将在所有请求结束时被调用。现在在这个函数中,我检查干净关闭的条件,如果满足,我什么都不做,输出刷新到浏览器,否则缓冲区被清理,只发送重定向到错误页面的 header 。

此代码的简化版本:

<?php
function redirect_on_error(){
if(!defined('EVERYTHING_WENT_OK')){
ob_end_clean();
header('Location: error.html');
}
}

register_shutdown_function('redirect_on_error');

ob_start();

include 'some/working/code.php';

echo "Now I'm going to call undefined function or throw something bad";

undefined_function();
throw new Exception('In case undefined function is defined.');

define('EVERYTHING_WENT_OK', TRUE);
exit;

关于PHP自定义错误页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5033436/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com