Ubuntu上PHP調試的常用方法
php.ini
文件(通過php --ini
命令查找路徑),將display_errors = Off
改為display_errors = On
,并確保error_reporting = E_ALL
(顯示所有錯誤)。重啟Web服務器(Apache用sudo systemctl restart apache2
,Nginx+PHP-FPM用sudo systemctl restart php{版本號}-fpm && sudo systemctl restart nginx
)后,錯誤信息會直接顯示在瀏覽器中。php.ini
中設置log_errors = On
和error_log = /var/log/php_errors.log
(自定義日志路徑),錯誤信息會寫入該文件。使用tail -f /var/log/php_errors.log
實時查看日志,避免敏感信息泄露給用戶。print_r()
/var_dump()
:在代碼中插入print_r($variable)
或var_dump($variable)
,輸出變量值或數組結構。適合快速檢查變量狀態,但需手動刪除調試代碼。error_log('調試信息', 0)
將自定義信息寫入error_log
文件,適合跟蹤代碼執行流程。Xdebug是PHP強大的調試擴展,支持斷點、變量查看、堆棧跟蹤等功能,需結合IDE(如PhpStorm、VSCode)使用。
通過Ubuntu包管理器安裝(推薦):
sudo apt-get update
sudo apt-get install php-xdebug # 根據PHP版本調整,如php8.2-xdebug
或通過PECL安裝(需提前安裝php-pear
和php-dev
):
sudo pecl install xdebug
編輯php.ini
文件,添加以下配置(根據PHP版本調整路徑):
[Xdebug]
zend_extension=xdebug.so # 自動加載擴展(包管理器安裝時無需指定路徑)
xdebug.mode=debug # 啟用調試模式
xdebug.client_host=127.0.0.1 # 調試客戶端地址(本地為127.0.0.1)
xdebug.client_port=9003 # 調試端口(默認9003,需與IDE一致)
xdebug.start_with_request=yes # 自動啟動調試(或設為"trigger"通過Cookie觸發)
xdebug.idekey=PHPSTORM # IDE標識(如PHPStorm、VSCode)
重啟Web服務器使配置生效。
.vscode/launch.json
文件,添加以下配置:{
"version": "0.2.0",
"configurations": [
{
"name": "Listen for Xdebug",
"type": "php",
"request": "launch",
"port": 9003,
"stopOnEntry": false,
"log": true,
"pathMappings": {
"/var/www/html": "${workspaceFolder}" // 映射項目路徑(服務器路徑:本地路徑)
}
}
]
}
http://localhost/index.php
),代碼執行到斷點時會暫停。display_errors
(設為Off
),避免泄露敏感信息。xdebug.mode
設為off
)。sudo ufw allow 9003
。