php – phpStorm 設定 debug

以 xdebug 為例,如果是在 windows ,例如使用 XAMPP 套件,可以參考官方網站這麼設定。
修改 php.ini 啟動 Xdebug
前往 Settings (Ctrl + Alt + S) > Languages & Frameworks > PHP 打開 php.ini


如果有以下,請把 Zend Debugger 和 Zend Optimizer 隱藏,也就是在前方加分號
1 2 3 4 |
zend_extension=<path_to_zend_debugger> zend_extension=<path_to_zend_optimizer> |
我們要啟動 Xdebug 所以在 php.ini 底部添加 Xdebug 章節,例如
1 2 3 4 5 6 |
[xdebug] zend_extension="C:\xampp\php\ext\php_xdebug-2.7.1-7.3-vc15.dll" xdebug.remote_enable=1 <--- 開啟可遠端控制 xdebug.remote_port=9911 <--- 指定一個沒用到的 port ,這是提供 phpStorm 連入 (預設9000) |
儲存並關閉設定,我們可以查看 xdebug 是否啟動
1 2 3 |
php --version |
1 2 3 4 5 6 |
PHP 7.3.1 (cli) (built: Jan 9 2019 22:43:14) ( ZTS MSVC15 (Visual C++ 2017) x86 ) Copyright (c) 1997-2018 The PHP Group Zend Engine v3.3.1, Copyright (c) 1998-2018 Zend Technologies with Xdebug v2.7.1, Copyright (c) 2002-2019, by Derick Rethans |
寫入一支 php 查看是否已經出現 xdebug 安裝的資訊
1 2 3 4 |
<?php phpinfo(); |

在 phpStorm 設定
參考官方文章,Settings (Ctrl + Alt + S) > Languages & Frameworks > PHP
如果 Xdebug 有正確安裝的話會看到以下版本正確的顯示。如果沒有正確安裝,會顯示 Debugger: Not installed

接著設定 port ,也就是我們在 php.ini 寫入的 xdebug.remote_port=9911

儲存設定後關閉。接著我們使用 Chrome 來瀏覽 PHP 專案,所以我們要安裝瀏覽器輔助套件 xdebug-helper 。其他瀏覽器可參考官網的列表。
安裝完成以後,我們寫段 Script
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 26 27 28 |
<?php session_start(); class Cart { public function __construct() { $_SESSION['cart'] = []; } public function add(array $params): string { $id = strtoupper(uniqid()); $_SESSION['cart'][$id] = $params; return $id; } public function all() { return $_SESSION['cart']; } } $cart = new Cart(); $firstId = $cart->add(['id' => 123, 'title' => 'Product']); $secondId = $cart->add(['id' => 456, 'title' => 'GOGORO']); $items = $cart->all(); print_r($items); |
接著設定斷點,準備觀察

點選右上角視窗電話符號,或是選單 Run > Start Listening for PHP Debug Connections 準備監聽

打開 Chrome 啟動套件 Debug

接著運行網頁,phpStorm 就會自動出現除錯模式,點擊不同按紐,可以直接查看變數

例如

不斷點擊按紐,可以看到斷點呈現的變數資訊,到結束時,若 PHP 有輸出指令,可以在 output 檢視結果。
Ububtu 安裝 Xdebug
1 2 3 4 5 |
sudo aptitude install php7.3-dev sudo aptitude install php-pear sudo pecl channel-update pecl.php.net |
安裝好後會看到這樣的訊息,要你前往添加 php.ini 的參數 zend_extension
1 2 3 4 5 6 7 |
Build process completed successfully Installing '/usr/lib/php/20170718/xdebug.so' install ok: channel://pecl.php.net/xdebug-2.7.2 configuration option "php_ini" is not set to php.ini location You should add "zend_extension=/usr/lib/php/20170718/xdebug.so" to php.ini |
當然也可以查詢 extension 安裝在哪個目錄
1 2 3 4 |
php-config --extension-dir // 例如我的顯示 /usr/lib/php/20170718 |
接著依照指示修改 php.ini,記得兩處都要
1 2 3 4 |
sudo vim /etc/php/7.3/cli/php.ini sudo vim /etc/php/7.3/apache2/php.ini |
如果已經有 zend_extension 參數,記得註解掉,我們改用以下
1 2 3 4 5 6 |
[xdebug] zend_extension="/usr/lib/php/20170718/xdebug.so" xdebug.remote_enable=1 <--- 開啟可遠端控制 xdebug.remote_port=9911 <--- 指定一個沒用到的 port ,這是提供 phpStorm 連入 (預設9000) |