在 Ubuntu 上定位 PHP 错误,通常可以从 PHP 错误日志、Web 服务器日志、PHP 配置 三个方面入手。下面按常见场景给你一套实用方法。
php --ini
常见位置:
/etc/php/8.1/cli/php.ini(命令行)/etc/php/8.1/fpm/php.ini(PHP-FPM)/etc/php/8.1/apache2/php.ini(Apache)查看错误相关配置:
grep -E "error_reporting|display_errors|log_errors|error_log" /etc/php/8.1/fpm/php.ini
关键参数说明:
error_reporting = E_ALL
display_errors = Off # 生产环境建议 Off
log_errors = On
error_log = /var/log/php/php-error.log
如果
error_log为空,错误会写入 Web 服务器日志。
tail -f /var/log/php/php-error.log
或
journalctl -u php8.1-fpm -f
tail -f /var/log/apache2/error.log
tail -f /var/log/nginx/error.log
tail -f /var/log/php/php-error.log
tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log
tail -f /var/log/apache2/access.log
tail -f /var/log/apache2/error.log
php your_script.php
若没输出错误:
php -d display_errors=1 your_script.php
在 PHP 文件顶部加:
ini_set('display_errors', 1);
error_reporting(E_ALL);
或在 CLI 临时执行:
php -d display_errors=1 -d error_reporting=E_ALL script.php
nginx/error.logphp-error.logphp -l file.php
tail -f /var/log/php/php-error.log
# Permission denied
解决办法:
chown -R www-data:www-data /path
chmod -R 755 /path
# 1. 看实时错误
tail -f /var/log/php/php-error.log
# 2. 看 Web 服务错误
tail -f /var/log/nginx/error.log
# 3. 复现请求
curl https://your-site.com/api/test
# 4. 根据报错行号定位代码
如果你愿意,可以告诉我:
我可以直接帮你给出对应命令和解决方案。