Ubuntu下ThinkPHP运行错误的排查与修复指南
一 快速定位与通用修复
- 开启调试与错误显示:在应用根目录的 .env 或 config/app.php 中将 app_debug=true;同时在入口或公共引导位置临时加入 error_reporting(E_ALL); ini_set(‘display_errors’,‘On’);,即可在页面看到具体报错与堆栈。
- 查看日志:优先检查 runtime/log/ 下的应用日志;同时查看 /var/log/php/fpm.log* 或 /var/log/apache2/error.log 等 Web/PHP 错误日志,定位语法、扩展、权限等问题。
- 清理缓存:删除 runtime/cache/、runtime/temp/ 等可写目录内容,避免异常缓存导致白屏或路由异常。
- 核对PHP版本:确保与所用框架版本匹配(如 ThinkPHP 6.x 需 PHP ≥ 7.2.5;早期版本如 5.0+ 需 PHP ≥ 5.6)。
- 安装常用扩展:至少启用 pdo_mysql、mbstring、curl、openssl、gd 等扩展,避免验证码、数据库、远程请求等功能异常。
二 环境与依赖检查
- 安装与启用扩展(示例为 Ubuntu 20.04+ 常见版本,按实际 PHP 版本调整包名):
- sudo apt-get update
- sudo apt-get install php php-fpm php-mysql php-mbstring php-xml php-curl php-gd
- 检查扩展是否生效:php -m | grep -E ‘pdo_mysql|mbstring|curl|openssl|gd’
- Web 服务要点:
- Apache:启用 mod_rewrite,并确保项目目录 AllowOverride All。
- Nginx:使用 PHP-FPM,常见套接字为 /var/run/php/php7.4-fpm.sock(以实际版本为准)。
三 服务器与重写配置
- Apache:在项目根目录放置或确认 .htaccess 内容类似:
-
- Options +FollowSymlinks -Multiviews
- RewriteEngine On
- RewriteCond %{REQUEST_FILENAME} !-f
- RewriteCond %{REQUEST_FILENAME} !-d
- RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
-
并确保站点配置 AllowOverride All 且已启用 rewrite 模块。
- Nginx:在 server 配置中加入:
- location / { try_files $uri $uri/ /index.php?$query_string; }
- location ~ .php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; }
- 修改后重启服务:sudo systemctl restart apache2 或 sudo systemctl restart nginx。
四 目录权限与路径问题
- 设置运行用户与权限(以 www-data 为例):
- sudo chown -R www-data:www-data /path/to/project
- sudo chmod -R 755 /path/to/project
- 确保 runtime/ 及子目录可写:chmod -R 755 runtime(必要时仅放宽到 runtime 目录)。
- 避免全站 777 权限,防止安全风险。
- 大小写敏感:Linux 文件系统区分大小写,控制器/文件名与调用路径需完全一致,避免因大小写导致的“类不存在”。
五 数据库与验证码专项排查
- 数据库:核对 config/database.php 中 hostname、database、username、password、port 等;确保数据库服务运行且允许当前主机连接;远程库需检查防火墙与授权;建议用 .env 管理敏感信息。
- 验证码不显示或缺字符:安装 GD 扩展 并确认启用;检查 session 保存路径 可写;排查文件 UTF-8 BOM 导致输出异常(可用命令 grep -r -I -l ‘\xEF\xBB\xBF’ ./ 查找并清除);如使用 ThinkPHP 5.1 自带的验证码需通过 composer require topthink-captcha 安装扩展。