如何让PHP错误显示出来

如何让PHP错误显示出来

技术背景

在PHP开发过程中,及时发现和解决代码中的错误至关重要。然而,默认情况下,PHP可能不会显示所有错误,特别是在生产环境中。因此,了解如何配置PHP以显示错误对于开发和调试非常重要。

实现步骤

开发环境(DEV environment)

  1. 使用代码设置:在PHP脚本中添加以下代码,可显示大多数错误,但无法显示当前文件中的解析错误。
1
2
3
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
  1. 修改php.iniphp-fpm.conf:若要显示解析错误,需修改配置文件。在php.ini中添加或修改以下行:
1
display_errors = on

若无法访问php.ini,可在.htaccess文件中添加:

1
php_flag display_errors 1

生产环境(PROD environment)

在生产环境中,为了安全起见,应关闭错误显示并开启错误日志记录。在php.ini中设置:

1
2
display_errors = off
log_errors = on

之后可在错误日志中查看所有错误。

AJAX调用

  • 开发服务器:打开开发者工具(F12),切换到“网络”选项卡。发起请求后,在“网络”选项卡中点击该请求,然后切换到“响应”选项卡查看具体输出。
  • 生产服务器:查看错误日志。

核心代码

捕获PHP 7中的错误和异常

1
2
3
4
5
6
7
try{
// Your code
}
catch(Error $e) {
$trace = $e->getTrace();
echo $e->getMessage().' in '.$e->getFile().' on line '.$e->getLine().' called from '.$trace[0]['file'].' on line '.$trace[0]['line'];
}

若要同时捕获异常和错误(不兼容PHP 5):

1
2
3
4
5
6
7
try{
// Your code
}
catch(Throwable $e) {
$trace = $e->getTrace();
echo $e->getMessage().' in '.$e->getFile().' on line '.$e->getLine().' called from '.$trace[0]['file'].' on line '.$trace[0]['line'];
}

自定义错误处理函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function ERR_HANDLER($errno, $errstr, $errfile, $errline){
$msg = "<b>Something bad happened.</b> [$errno] $errstr <br><br>
<b>File:</b> $errfile <br>
<b>Line:</b> $errline <br>
<pre>".json_encode(debug_backtrace(), JSON_PRETTY_PRINT)."</pre> <br>";

echo $msg;

return false;
}

function EXC_HANDLER($exception){
ERR_HANDLER(0, $exception->getMessage(), $exception->getFile(), $exception->getLine());
}

function shutDownFunction() {
$error = error_get_last();
if ($error["type"] == 1) {
ERR_HANDLER($error["type"], $error["message"], $error["file"], $error["line"]);
}
}

set_error_handler ("ERR_HANDLER", E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
register_shutdown_function("shutdownFunction");
set_exception_handler("EXC_HANDLER");

最佳实践

  1. 根据环境配置:在开发环境中开启错误显示,方便调试;在生产环境中关闭错误显示,开启错误日志记录。
  2. 使用自定义错误处理函数:自定义错误处理函数可以提供额外的调试信息,还可以将错误信息通过邮件发送给开发者。
  3. 使用Xdebug:如果安装了Xdebug,可以通过设置以下参数覆盖所有错误显示设置:
1
2
xdebug.force_display_errors = 1;
xdebug.force_error_reporting = -1;

常见问题

  1. 无法显示解析错误:若使用代码设置无法显示解析错误,需修改php.ini.htaccess文件。
  2. 共享主机环境问题:在共享主机环境中,仅在.htaccess文件中添加php_flag display_errors 1可能无效,还需通过cPanel等工具编辑php.ini文件。
  3. Windows环境下的日志问题:使用XAMPP时,需手动创建C:\xampp\php\logs文件夹,以便记录错误日志。

如何让PHP错误显示出来
https://119291.xyz/posts/how-to-get-php-errors-to-display/
作者
ww
发布于
2025年5月23日
许可协议