---
title: "显示所有 PHP 错误并抓住访客从未看到的错误"
description: "PHP 错误要么显示在页面上，要么写进错误日志，由 php.ini 决定。用生产环境的 php.ini 时，我们的 5 个错误中有 4 个让访客拿到空的 500 页面，只有错误日志留下了这些错误。"
canonical: "https://logbrew.co/zh-Hans/errors/php"
last_updated: "2026-11-25"
---

# 显示所有 PHP 错误并抓住访客从未看到的错误

PHP 错误要么显示在页面上，要么写进错误日志，由 php.ini 决定。用生产环境的 php.ini 时，我们的 5 个错误中有 4 个让访客拿到空的 500 页面，只有错误日志留下了这些错误。

开发时把 `display_errors` 设为 `On`，把 `error_reporting` 设为 `E_ALL`。生产环境中不要把错误显示在页面上，去读错误日志。

2026年11月25日 用 PHP 8.5.6、logbrew/sdk 0.1.26、Composer 2.10.0和logbrew CLI 0.1.96 实测

Canonical: https://logbrew.co/zh-Hans/errors/php

## 哪些 PHP 错误到达了 LogBrew

| PHP 错误 | 只用 `set_exception_handler` | 3 个处理函数都用 |
| --- | --- | --- |
| 警告，未定义的变量 | 没有 | 日志 |
| 未捕获的 `RuntimeException` | 问题 | 问题 |
| 未定义的函数 | 问题 | 问题 |
| 内存上限 | 没有 | 问题 |
| 语法错误 | 没有 | 问题 |

使用生产环境 php.ini 的 PHP 8.5.6 中的 5 个错误，由 logbrew/sdk 0.1.26 发送到本地 LogBrew API。

## 开发时显示每个错误

### 在脚本开头打开错误显示

用生产环境的 php.ini 时，`display_errors` 是 `Off`。我们那个含未定义变量的页面输出了空值，没有警告。在文件开头加上这 3 行后，页面上显示了警告。

```bash
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
```

输出

```text
<br />
<b>Warning</b>:  Undefined variable $discount in <b>…/shop/public/cart.php</b> on line <b>7</b><br />
Items: 3, discount: 
cart page finished
```

### 在 php.ini 中设置才能看到语法错误

PHP 要先解析完文件，才会执行 `ini_set()`。同一个文件里少一个 `;`，仍然得到空白的 500 页面。把同样的值写进 php.ini，然后重启 PHP-FPM 或 Web 服务器。

```bash
display_errors = On
display_startup_errors = On
error_reporting = E_ALL
```

输出

```text
<br />
<b>Parse error</b>:  syntax error, unexpected token &quot;echo&quot; in <b>…/shop/public/invoice.php</b> on line <b>3</b><br />
```

### 找到 PHP 加载的 php.ini

命令行和 Web 服务器可能加载不同的文件。`php --ini` 显示命令行用的文件。Web 服务器用的文件，可以在页面里输出 `php_ini_loaded_file()` 来查看。

```bash
php --ini
```

输出

```text
Configuration File (php.ini) Path: "/opt/homebrew/etc/php/8.5"
Loaded Configuration File:         "/opt/homebrew/etc/php/8.5/php.ini"
Scan for additional .ini files in: "/opt/homebrew/etc/php/8.5/conf.d"
Additional .ini files parsed:      (none)
```

## 生产环境中记录错误日志

### 对访客隐藏错误，并写进日志

保持 `display_errors` 为 `Off`，访客就看不到文件路径或查询语句。打开 `log_errors`，给 `error_log` 指定一个 PHP 能写入的文件。

```bash
display_errors = Off
log_errors = On
error_log = /var/log/php/error.log
```

### 查看错误日志

每个空白的 500 页面都在日志里留下了错误。PHP 8.5 还会为内存上限这类致命错误写出堆栈。

```bash
tail -n 20 /var/log/php/error.log
```

输出

```text
[25-Nov-2026 09:11:29 UTC] PHP Warning:  Undefined variable $discount in …/shop/public/cart.php on line 3
[25-Nov-2026 09:11:29 UTC] PHP Fatal error:  Uncaught RuntimeException: Payment API timed out in …/shop/public/checkout.php:3
Stack trace:
#0 {main}
  thrown in …/shop/public/checkout.php on line 3
[25-Nov-2026 09:11:29 UTC] PHP Fatal error:  Uncaught Error: Call to undefined function send_receipt() in …/shop/public/receipt.php:2
Stack trace:
#0 {main}
  thrown in …/shop/public/receipt.php on line 2
[25-Nov-2026 09:11:29 UTC] PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 153000032 bytes) in …/shop/public/export.php on line 2
Stack trace:
#0 …/shop/public/export.php(2): str_repeat()
#1 {main}
[25-Nov-2026 09:11:29 UTC] PHP Parse error:  syntax error, unexpected token "echo" in …/shop/public/invoice.php on line 3
```

## 把每个错误发送到 LogBrew

### 安装 LogBrew PHP SDK

SDK 需要 PHP 8.2 或更高版本。

```bash
composer require logbrew/sdk
```

### 在 1 个文件中加上 3 个处理函数

`set_exception_handler` 能收到未捕获的异常和 `Error`，但收不到内存上限这类致命错误。PHP 停止脚本后，`register_shutdown_function` 用 `error_get_last()` 读出这个错误。`set_error_handler` 把每条警告作为日志发送。把 `LOGBREW_INGEST_KEY` 设为项目的一个 `server` 密钥。

```bash
<?php
require __DIR__ . '/vendor/autoload.php';

use LogBrew\HttpTransport;
use LogBrew\IssueDiagnostics;
use LogBrew\LogBrewClient;
use LogBrew\SdkError;

$logbrew = LogBrewClient::create((string) getenv('LOGBREW_INGEST_KEY'), 'shop', '1.0.0');
$id = static fn (): string => 'evt_' . bin2hex(random_bytes(8));
$now = static fn (): string => gmdate('Y-m-d\TH:i:s\Z');

set_error_handler(static function (int $type, string $message) use ($logbrew, $id, $now): bool {
    $logbrew->log($id(), $now(), ['message' => $message, 'level' => 'warning', 'logger' => 'php']);
    return false;
});

set_exception_handler(static function (Throwable $error) use ($logbrew, $id, $now): void {
    error_log('PHP Fatal error:  Uncaught ' . $error);
    http_response_code(500);
    $logbrew->issue($id(), $now(), IssueDiagnostics::fromThrowable($error, mechanismType: 'php.uncaught', handled: false));
});

register_shutdown_function(static function () use ($logbrew, $id, $now): void {
    $error = error_get_last();
    if ($error !== null && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR], true)) {
        $logbrew->issue($id(), $now(), ['title' => 'PHP Fatal error', 'level' => 'fatal', 'message' => $error['message']]);
    }
    try {
        $logbrew->shutdown(new HttpTransport());
    } catch (SdkError $failure) {
        error_log('LogBrew: ' . $failure->getMessage());
    }
});
```

### 在每个脚本之前加载这个文件

在 php.ini 中设置 `auto_prepend_file`，或者在前端控制器的第一行 `require` 这个文件。

```bash
auto_prepend_file = /var/www/shop/logbrew.php
```

### 保留日志行和 500 状态码

设置了异常处理函数后，PHP 不再往日志里写 `PHP Fatal error:  Uncaught`。没有下面这 2 行，我们的结账页面还会返回 `200` 和空页面。加上这 2 行后，日志行和 `500` 都回来了。

```bash
error_log('PHP Fatal error:  Uncaught ' . $error);
http_response_code(500);
```

输出

```text
HTTP/1.1 500 Internal Server Error
[25-Nov-2026 09:18:11 UTC] PHP Fatal error:  Uncaught RuntimeException: Payment API timed out in …/shop/public/checkout.php:3
Stack trace:
#0 {main}
```

### 用 LogBrew CLI 查看错误

每个异常和致命错误是 1 个问题，每条警告是 1 条日志。

```bash
logbrew read issues --project "<project_id>" --since 1h
logbrew read logs --project "<project_id>" --since 1h
```

输出

```text
Issues (4)
- 2dfc15b0-33bc-5fae-ba66-3defb0871e39 unresolved error priority=medium Error in receipt.php:2 occurrences=1 users=unknown last_seen=2026-11-25T09:18:11Z service=unknown_service trace=3deaceb311395198c2bd5a33389ef2e3 assignee=unassigned [unversioned / production]
- 1a4b7e84-6dc3-5f23-a861-1c9e2c03f55e unresolved error priority=medium RuntimeException occurrences=1 users=unknown last_seen=2026-11-25T09:18:11Z service=unknown_service trace=dde520aa061f3ad867b0b55ceb5c13aa assignee=unassigned [unversioned / production]
- 4de1364d-e748-5dfe-9be8-80bd8ede83aa unresolved critical priority=high PHP Fatal error occurrences=1 users=unknown last_seen=2026-11-25T09:18:11Z service=unknown_service trace=e82dfd4169caebdff0414cdfafd53314 assignee=unassigned [unversioned / production]
- d8192abc-8c98-54e5-9b95-424c89593aeb unresolved critical priority=high PHP Fatal error occurrences=1 users=unknown last_seen=2026-11-25T09:18:11Z service=unknown_service trace=3424e320bf52d61aa14204424f3ae127 assignee=unassigned [unversioned / production]
Logs (1)
- warning Undefined variable $discount service=unknown_service trace=18ac51390e834d7c3cfd36ab4cb8f48a [unversioned / production]
```

## 我们测试时看到的结果

我们在 macOS 27.2 上运行 PHP 8.5.6，使用内置 Web 服务器和 PHP 自带的 `php.ini-production` 文件。5 个页面各有 1 个错误，用 curl 8.7.1 把每个页面各请求一次。

只有含警告的页面返回 `200`。其余 4 个返回 `500` 和 0 字节，错误日志为全部 5 个都留下了一行。`display_errors` 为 `On` 时，PHP 把每个错误都显示在页面上并返回 `200`，致命错误也一样。

|  | HTTP | PHP error log |
| --- | --- | --- |
| 警告 | `200` | `PHP Warning` |
| 未捕获的异常 | `500` | `PHP Fatal error` |
| 未定义的函数 | `500` | `PHP Fatal error` |
| 内存上限 | `500` | `PHP Fatal error` |
| 语法错误 | `500` | `PHP Parse error` |

## 为什么 set_exception_handler 收不到致命错误

从 PHP 7 起，大多数错误都是 `Error` 异常，比如调用未定义的函数，`set_exception_handler` 能收到它们。但仍有一些错误会立刻停止脚本，比如内存上限和所请求文件中的语法错误。这些错误任何处理函数都收不到。

PHP 停止脚本后仍会运行关闭函数。这时 `error_get_last()` 会返回这个错误的类型、消息、文件和行号。

1. PHP 停止脚本
2. PHP 运行关闭函数
3. error_get_last() 返回错误

## LogBrew 记录了什么

LogBrew 把每个未捕获的异常保存为 1 个问题，带有异常类型、作为机制的 `php.uncaught`，以及只含文件名的堆栈帧，比如 `checkout.php` 第 3 行。SDK 默认不发送异常消息，因为消息里可能有用户数据。确认消息安全时，给 `fromThrowable()` 传入 `message:`。

关闭函数把内存上限和语法错误作为问题发送，级别为 `critical`，并带上 PHP 的消息。控制台、CLI 和 MCP 服务器都能像读取其他 LogBrew 问题一样读取它们。

- `RuntimeException`
  - `level`: `error`
  - `exception.type`: `RuntimeException`
  - `mechanism`: `php.uncaught`
  - `handled`: `false`
  - 堆栈帧: 1
  - `messageState`: `redacted`
- `PHP Fatal error`
  - `level`: `critical`
  - 消息: `Allowed memory size of 134217728 bytes exhausted …`

## 常见问题

### 如何在 PHP 中显示所有错误？

在 php.ini 中设置 `display_errors = On`、`display_startup_errors = On` 和 `error_reporting = E_ALL`，然后重启 PHP。在脚本开头用 `ini_set()` 也可以，但显示不了同一文件里的语法错误。

### 为什么我的 PHP 页面一片空白？

一个致命错误停止了脚本，而 `display_errors` 是 `Off`，所以 PHP 返回了空的 500 页面。错误在 PHP 错误日志里。

### PHP 错误日志在哪里？

就是 `error_log` 设置里的那个文件。没有设置时，PHP 把错误发到 Web 服务器的错误日志，命令行下则输出到 stderr。

### set_exception_handler 能捕获致命错误吗？

它能收到 `Error` 异常，比如调用未定义的函数。它收不到内存上限和语法错误。这些错误要用 `register_shutdown_function` 配合 `error_get_last()`。

### PHP 警告和致命错误有什么区别？

出现警告后，PHP 会继续运行脚本的其余部分。出现致命错误后，PHP 会停止脚本。我们含警告的页面返回 `200`，每个致命错误都返回 `500`。

## 在 1 个地方追踪每个 PHP 错误

用 PHP SDK 把 PHP 异常、致命错误和警告发送到 LogBrew，然后在控制台、CLI 或你的 AI 智能体中查看。免费额度充足，无需绑卡。

[免费开始](https://logbrew.co/zh-Hans)

## 参考来源

- [PHP manual, Errors and Logging Configuration](https://www.php.net/manual/en/errorfunc.configuration.php)
- [php/php-src, php.ini-production (PHP-8.5)](https://github.com/php/php-src/blob/PHP-8.5/php.ini-production)
- [PHP manual, Error](https://www.php.net/manual/en/class.error.php)
- [PHP manual, set_exception_handler](https://www.php.net/manual/en/function.set-exception-handler.php)
- [PHP manual, register_shutdown_function](https://www.php.net/manual/en/function.register-shutdown-function.php)
- [PHP manual, error_get_last](https://www.php.net/manual/en/function.error-get-last.php)
- [LogBrewCo/sdk, php/logbrew-php](https://github.com/LogBrewCo/sdk/tree/main/php/logbrew-php)

## 修复错误

- [修复隐藏了消息、文件和行号的脚本错误](https://logbrew.co/zh-Hans/errors/script-error)
- [修复 Failed to fetch 错误，分清它的 3 种原因](https://logbrew.co/zh-Hans/errors/failed-to-fetch)
- [从消息入手修复 Kotlin 和 Android 中的 java.lang.NullPointerException](https://logbrew.co/zh-Hans/errors/nullpointerexception)
- [从完整消息和你自己的代码行入手修复 Minified React error #418 和 #185](https://logbrew.co/zh-Hans/errors/minified-react-error)
- [在浏览器和 Node.js 中修复 Cannot use import statement outside a module](https://logbrew.co/zh-Hans/errors/cannot-use-import-statement-outside-a-module)
- [修复 AxiosError Network Error，找出你遇到的是 3 种原因中的哪一种](https://logbrew.co/zh-Hans/errors/axios-network-error)
- [修复 HTTP 499 错误，找出是谁先停止了等待](https://logbrew.co/zh-Hans/errors/http-499)
- [修复 413 Request Entity Too Large，找出是哪一层拒绝了请求体](https://logbrew.co/zh-Hans/errors/http-413)
- [修复 nginx 的 504 Gateway Time-out，并找出是哪个超时到期了](https://logbrew.co/zh-Hans/errors/http-504)
- [我们复现过的错误，以及每个错误的修复方法](https://logbrew.co/zh-Hans/errors)
