Настройка xdebug phpstorm linux

Обновлено: 07.07.2024

Download the Xdebug extension compatible with your PHP version and install it as described in the installation guide.

Xdebug 3 brings performance improvements, simplified configuration, and PHP 8 support. To learn more on upgrading to Xdebug 3, see the Upgrade guide.

If you are using an AMP package, the Xdebug extension may be already installed. Refer to the instructions specific for your package.

Integrate Xdebug with the PHP interpreter

Open the active php.ini file in the editor:

In the Settings/Preferences dialog Ctrl+Alt+S , click PHP .

On the PHP page that opens, click next to the CLI Interpreter field.

In the CLI Interpreters dialog that opens, the Configuration file read-only field shows the path to the active php.ini file. Click Open in Editor .

To disable the Zend Debugger and Zend Optimizer tools, which block Xdebug, remove or comment out the following lines in the php.ini file:

zend_extension=<path_to_zend_debugger> zend_extension=<path_to_zend_optimizer>

To enable Xdebug, locate or create the [xdebug] section in the php.ini file and update it as follows:

[xdebug] zend_extension="<path to xdebug extension>" xdebug.remote_enable=1 xdebug.remote_host=127.0.0.1 xdebug.remote_port="<the port (9000 by default) to which Xdebug connects>" [xdebug] zend_extension="<path to xdebug extension>" xdebug.mode=debug xdebug.client_host=127.0.0.1 xdebug.client_port="<the port (9003 by default) to which Xdebug connects>"

In PHP 5.3 and later, you need to use only zend_extension , not zend_extension_ts , zend_extension_debug , or extension .

To enable multi-user debugging via Xdebug proxies, locate the xdebug.idekey setting and assign it a value of your choice. This value will be used to register your IDE on Xdebug proxy servers.

Save and close the php.ini file.

Verify Xdebug installation by doing any of the following:

In the command line, run the following command:

The output should list Xdebug among the installed extensions:

Create a php file containing the following code:

Open the file in the browser. The phpinfo output should contain the Xdebug section:

Configure Xdebug in PhpStorm

Press Ctrl+Alt+S to open the IDE settings and select PHP .

Check the Xdebug installation associated with the selected PHP interpreter:

On the PHP page, choose the relevant PHP installation from the CLI Interpreter list and click next to the field. The list shows all the PHP installations available in PhpStorm, see Configure local PHP interpreters and Configure remote PHP interpreters.

The CLI Interpreters dialog that opens shows the following:

The version of the selected PHP installation.

The name and version of the debugging engine associated with the selected PHP installation (Xdebug or Zend Debugger). If no debugger is configured, PhpStorm shows the corresponding message:

Alternatively, open the Installation Wizard, paste the output of the phpinfo() , and click Analyze my phpinfo() output . Learn more about checking the Xdebug installation in Validate the Configuration of a Debugging Engine.

Define the Xdebug behaviour. Click Debug under the PHP node. On the Debug page that opens, specify the following settings in the Xdebug area:

In the Debug port field, appoint the port through which the tool will communicate with PhpStorm.

This must be the same port number as specified in the php.ini file:

xdebug.remote_port="<the port (9000 by default) to which Xdebug connects>" xdebug.client_port="<the port (9003 by default) to which Xdebug connects>"

By default, Xdebug 2 listens on port 9000 . For Xdebug 3, the default port has changed from 9000 to 9003 . You can specify several ports by separating them with a comma. By default, the Debug port value is set to 9001,9003 to have PhpStorm listen on both ports simultaneously.

To have PhpStorm accept any incoming connections from Xdebug engine through the port specified in the Debug port field, select the Can accept external connections checkbox.

Select the Force break at first line when no path mapping specified checkbox to have the debugger stop as soon as it reaches and opens a file that is not mapped to any file in the project on the Servers page. The debugger stops at the first line of this file and Examine/update variables shows the following error message: Cannot find a local copy of the file on server <path to the file on the server> and a link Click to set up mappings . Click the link to open the Resolve Path Mappings Problem dialog and map the problem file to its local copy.

When this checkbox cleared, the debugger does not stop upon reaching and opening an unmapped file, the file is just processed, and no error messages are displayed.

Select the Force break at first line when a script is outside the project checkbox to have the debugger stop at the first line as soon as it reaches and opens a file outside the current project. With this checkbox cleared, the debugger continues upon opening a file outside the current project.

In the External connections area, specify how you want PhpStorm to treat connections received from hosts and through ports that are not registered as deployment server configurations.

Ignore external connections through unregistered server configurations : Select this checkbox to have PhpStorm ignore connections received from hosts and through ports that are not registered as deployment server configurations. When this checkbox is selected, PhpStorm does not attempt to create a deployment server configuration automatically.

Break at first line in PHP scripts : Select this checkbox to have the debugger stop as soon as connection between it and PhpStorm is established (instead of running automatically until the first breakpoint is reached). Alternatively turn on the Run | Break at first line in PHP scripts option from the main menu.

Max. simultaneous connections Use this spin box to limit the number of external connections that can be processed simultaneously.

By default, PhpStorm only listens for incoming IPv4 connections. To enable IPv6 support, you need to make adjustments in PhpStorm JVM options:

Select Help | Edit Custom VM Options from the main menu.

Configure Xdebug for using in the On-Demand mode

PhpStorm supports the On-Demand mode, where you can disable Xdebug for your global PHP installation and have it enabled automatically on demand only when you are debugging your command-line scripts or when you need code coverage reports. This lets your command line scripts (including Composer and unit tests) run much faster.

Disable Xdebug for command-line scripts:

In the Settings/Preferences dialog Ctrl+Alt+S , go to PHP .

From the PHP executable list, choose the relevant PHP interpreter and click next to it. In the CLI Interpreters dialog that opens, click the Open in Editor link next to the Configuration file: <path to php.ini> file. Close all the dialogs and switch to the tab where the php.ini file is opened.

In the php.ini file, find the [xdebug] section and comment the following line in it by adding ; in preposition:

Open the CLI Interpreters dialog and click next to the PHP executable field. PhpStorm informs you that debugger is not installed:

To enable PhpStorm to activate Xdebug when it is necessary, specify the path to it in the Debugger extension field, in the Additional area. Type the path manually or click and select the location in the dialog that opens.

Configure Xdebug for using in the Just-In-Time mode

PhpStorm supports the use of Xdebug in the Just-In-Time (JIT) mode so it is not attached to your code all the time but connects to PhpStorm only when an error occurs or an exception is thrown. Depending on the Xdebug version used, this operation mode is toggled through the following settings:

Xdebug 2 uses the xdebug .remote_mode setting, which has to be set to jit .

Xdebug 3 uses the xdebug.start_upon_error setting, which has to be set to yes .

The mode is available both for debugging command-line scripts and for web server debugging.

Depending on whether you are going to debug command-line scripts or use a Web server, use one of the scenarios below.

Command-line scripts

For debugging command-line scripts, specify the custom -dxdebug.remote_mode=jit (for Xdebug 2) or -dxdebug.start_upon_error=yes (for Xdebug 3) directive as an additional configuration option :

Press Ctrl+Alt+S to open the IDE settings and select PHP .

From the PHP executable list, choose the relevant PHP interpreter and click next to it.

In the CLI Interpreters dialog that opens, click next to the Configuration options field in the Additional area.

In the Configuration Options dialog that opens, click to add a new entry.

For Xdebug 2, type xdebug.remote_mode in the Configuration directive field and jit in the Value field.

For Xdebug 3, type xdebug.start_upon_error in the Configuration directive field and yes in the Value field.

When you click OK , you return to the CLI Interpreters dialog where the Configuration options field shows -dxdebug.remote_mode=jit (for Xdebug 2) or -dxdebug.start_upon_error=yes (for Xdebug 3).

Web server debugging

From the main menu, choose Run | Web Server Debug Validation .

In the Validate Remote Environment that opens, choose the Web server to validate the debugger on.

Path to Create Validation Script : In this field, specify the absolute path to the folder under the server document root where the validation script will be created. For Web servers of the type Inplace , the folder is under the project root.

Deployment Server : In this field, specify the server access configuration of the type Local Server or Remote Server to access the target environment. For details, see Configure synchronization with a Web server.

Choose a configuration from the list or click Browse in the Deployment dialog.

Click Validate to have PhpStorm create a validation script, deploy it to the target remote environment, and run it there.

Open the php.ini file which is reported as loaded and associated with Xdebug.

In the php.ini file, find the [xdebug] section.

Change the value of the xdebug.remote_mode from the default req to jit .

Change the value of the xdebug.start_upon_error from the default default to yes .

Configure Xdebug running in a Docker container

To configure Xdebug running in a Docker container, provide the Xdebug-specific parameters in the Dockerfile , for example:

Отладка - один из самых важных процессов в программировании. С помощью отладчика вы можете посмотреть что происходит в программе на самом деле, какие функции выполняются, что хранится в переменных, а также выполнить всё пошагово и точно понять на какой строчке и при каких значениях переменных случается ошибка.

Для языка программирования PHP используется отладчик Xdebug, PHPStorm - это одна из самых популярных сред разработки. В этой статье мы рассмотрим как настроить Xdebug в PhpStorm для отладки на локальном компьютере и в Docker.

Настройка Xdebug в PhpStorm

1. Отладка на локальном компьютере

Все настройки будут показаны на примере Ubuntu и интерпретатора PHP, настроенного вместе с Apache. Для других конфигураций пути к файлам могут отличаться, но суть останется та же. Давайте разберемся как это будет работать. Отладчик Xdebug позволяет приостанавливать выполнение кода, смотреть стек вызовов и содержимое переменных. Однако удобного интерфейса управления у него нет. Поэтому для управления отладкой будем использовать IDE. Но IDE не может никак сообщить отладчику что надо запустить отладку, потому что она отвечает только за код. Для этого понадобится ещё расширение для браузера Debug Helper, с помощью которого вы сможете включить режим отладки.

Сначала необходимо установить Xdebug. Для этого выполните:

sudo apt install xdebug

После завершения установки Xdebug надо настроить программу так, чтобы при запуске сеанса отладки она пыталась подключится к нашей IDE для управления отладкой. Для этого добавьте такие строчки в файл /etc/php/7.4/apache2/conf.d/20-xdebug.ini в версии Xdebug 2:

sudo vi /etc/php/7.4/apache2/conf.d/20-xdebug.ini

zend_extension=xdebug.so
xdebug.remote_enable=1
xdebug.remote_host=127.0.0.1
xdebug.remote_connect_back=1
xdebug.remote_port=9000
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.remote_autostart=false

Для новой версии Xdebug 3 старая конфигурация тоже будет работать, но лучше использовать новый стандарт:

xdebug.mode=debug
xdebug.start_with_request=trigger
xdebug.discover_client_host = false
xdebug.client_host = 127.0.0.1
xdebug.client_port = 9000

Давайте рассмотрим эти настройки подробнее. Первый параметр xdebug.mode - режим отладки, возможные варианты:

  • develop - включает вывод дополнительной информации, переопределяет var_dump;
  • debug - режим построчного выполнения кода, именно он нужен в данном случае;
  • profile - профилирование;
  • trace - трассировка выполнения программы.

Если необходимо, вы можете включить несколько режимов, перечислив их через запятую. Вторая строчка xdebug.start_with_request определяет как будет запускаться отладчик для режимов debug, trace и им подобных:

  • yes - всегда, при запуске php скриптов;
  • no - запуск только из кода с помощью специальных функций;
  • trigger - по запросу, с помощью специальной переменной в $_ENV, $_POST, $COOKIE или в другом массиве. Этот вариант подходит лучше всего в данном случае чтобы отладчик не запускался когда в этом нет необходимости.

sudo systemctl restart apache2

Теперь надо настроить PhpStorm. Запустите программу, затем откройте меню Run -> Edit Configurations. Перед вами откроется окно, в котором надо настроить отладчик.

В настройках можно ничего не менять, укажите только имя этого способа отладки. Если сервер, с которого будут ожидаться подключения не задать, то будут приниматься все подключения.

Если вам нужно изменить порт, к которому будет подключаться Xdebug откройте меню File -> Settings -> PHP -> Debug -> DBGp Proxy. Здесь можно указать нужный порт:

Теперь IDE готова. Кликните по значку жука на верхней панели инструментов чтобы программа начала ожидать подключения отладчика и поставьте несколько точек останова в коде просто кликнув перед строчкой с кодом:

Дальше осталось настроить браузер. Для Chrome можно скачать это расширение. Установите его и откройте страницу, которую надо отлаживать. Кликните по значку расширения и выберите Debug. Значок расширения станет зеленым:

Обновите страницу и возвращайтесь к PHPStorm. Если всё было сделано верно, там запустится сеанс отладки. При первом запуске программа может попросить настроить соответствия локальных путей к файлам с удаленными. Для локального сервера здесь ничего настраивать не надо, достаточно нажать Accept:

Дальше отладчик остановит выполнение на выбранной точке останова и в программе появится интерфейс отладки:

Как видите всё довольно просто. Дальше давайте разберемся как настроить Xdebug PhpStorm и Docker.

2. Отладка Php в Docker

C Docker возникает одна сложность. Поскольку отладчик должен сам подключится к IDE, необходимо пробросить хост в контейнер. В windows это можно сделать с помощью адреса host.docker.internal. Но в Linux, по умолчанию это не происходит. Для того чтобы добавить такой адрес надо добавить в docker-compose такие строчки:

Давайте для этого примера будем использовать такую структуру директорий:

Минимально необходимый docker-compose.yaml будет выглядеть вот так:

Здесь объявляется два контейнера, nginx и php-fpm. В первый не надо вносить никакие изменения, поэтому можно просто брать официальный образ, монтировать папку с исходниками, конфигурационный файл и пробрасывать порт. Во второй контейнер надо установить и настроить Xdebug поэтому его придется собрать на основе официального контейнера php. Для этого же контейнера надо указать директиву extra_hosts, без неё ничего работать не будет. Конфигурация Nginx тоже вполне стандартная:

Здесь настроена обработка PHP скриптов в контейнере php-fpm, и редирект несуществующих URL на index.php, что вполне стандартно для многих фреймворков и CMS. Самое интересное - Dockerfile контейнера php-fpm, он выглядит вот так:

FROM php:8.0.3-fpm-buster
RUN pecl install xdebug \
&& docker-php-ext-enable xdebug
COPY xdebug.ini /usr/local/etc/php/conf.d/xdebug.ini

Здесь устанавливается xdebug с помощью pecl, а затем копируется его конфигурационный файл в контейнер. Вот этот конфигурационный файл:

xdebug.mode=debug
xdebug.start_with_request=trigger
xdebug.discover_client_host = false
xdebug.client_host = host.docker.internal
xdebug.client_port = 9000

В контейнере установлен Xdebug 3 для PHP 8, потому что старая версия с этой версией языка уже не работает, поэтому используется новый синтаксис конфигурации. Ну и хост, host.docker.internal, который раньше был прописан в docker-compose.yaml. Настройка xdebug PHPStorm docker завершена. Дальше вы можете запустить проект:

docker-compose up --build

Теперь, как и в предыдущем варианте вы можете включить в браузере режим отладки, обновить страницу и отладчик успешно подключится к IDE, не смотря на то, что он работает в Docker:


Выводы

В этой статье мы рассмотрели как выполняется настройка xdebug PHPStorm на локальном компьютере и в Docker контейнере. Если всё сделать правильно отладчик будет работать и помогать вам искать ошибки в коде.

Нет похожих записей


Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна.

1. Установка xdebug.
Так как я использую php5.6 из стороннего репозитория я буду выполнять команду с жестко указанной версией php5.6. Если у Вас установлен PHP и каноникал репозитория путем типичной установки LAMP то вам не нужно указывать версию



2. Ищем путь к so файлу установленного xdebug командой:

Для тех у кого PHP установлен стандартным LAMP путем, вывод будет всего одной строкой типа
«/usr/lib/php/7.0/20131226/xdebug.so»

Копируем нужный нам путь, сохраняем временно где-то

3. Редакутируем PHP.INI
Открываем файл sudo nano /etc/php/X.X/apache2/php.ini где X.X версия установленного у вас PHP. Например для PHP-5.6 путь будет таким /etc/php/5.6/apache2/php.ini

В самый конец файла добавляем следующие записи:

Нажимаем Apply и OK. По желанию можно выбрать дефолтный браузер в котором будет открываться сессия xdebug, но меня устраивает выбор Chrome как браузера по умолчанию, по этому я пропускаю это действие.

5. Тестируем результат.


После успешного применения настроек у нас станут активные некоторые элементы управления типичными настройками xdebug

Открываем код Magento или любой другой CMS или своего проекта и ставим брейкпойнт в таком месте где вы точно убеждены что будет выполнен код PHP, как правило это всегда просто сделать в index.php. Для Magento я поставлю маркер (breakpoint) в файле index.php на строке



На этом все, если будут вопросы, пожалуйста, задавайте в комментариях. Удачи.

  1. Windows 10 (как основная система)
  2. Ubuntu 14.04.3 Guest System (Web server для разработки запущенный под VMWare Workstation 11)
  3. PHPStorm, установленный в Windows 10.

Задача использовать xdebug который будет находится в гостевой системе из под PHPSTORM Windows среды.
Приступим.
1. Установка xdebug на нашем сервере под управлением Ubuntu 14.04
Подключаемся к серверу по SSH, вводим следующую команду:

После ищем в какой директории установился xdebug

Далее в терминале открываем php.ini нашего сервера

В данном файле в самый низ добавляем заапись такого вида, естественно подставив свой путь к xdebug который Вам выдал терминал выше.

Теперь делаем рестарт сервера

Отлично, приступаем к настройке и привязке нашего xdebug к Windows среде и PHPStorm запущенного под Windows 10.

  1. Настройка связки External (Remote) PHP with xdebug + PHPStorm Windows.

Итак, теперь давайте внесем данный в php.ini о xdebug для того чтобы сервер понимал кого и куда перенаправлять.
Пишем в терминале гостевой ubuntu машины

Важно! Обратите внимание что в параметре xdebug.remote_host я использую свой IP адрес который я сделал статическим в своей Windows 10, как показал на скрине выше. Если Вы имеете другой IP адрес, то пожалуйста укажите в этом параметре его.

Сохраняем файл перезапускаем apache на гостевой машине

Screenshot_3

В открывшемся новом окне нажимаем сюда

Screenshot_5

В открывшемся окне воодим требуемые параметры подключения к гостевой машине серверу. У меня гостевой сервер, точно так же как и основная Windows система имеет статический IP 192.168.0.110 и находится в реальном сегменте сети, не под NAT. У вас, соответственно может быть другой адрес. В любом случае в данном окне нужно вводить непосредственно те данные, которые вы используете при стандартном подключении по SSH к гостевому серверу.

Screenshot_6

После того как заполнение формы закончено нажимаем ОК и видим следующее окно

Screenshot_7

Идем дальше. Теперь снова открываем окно настроек PHPStorm только уже вкладку Servers и нажимаем зеленый крестик:

Screenshot_8

Screenshot_9

Нажимаем Apply и OK. Идем дальше.
Теперь нам нужно создать Web Application для PHPStorm, которая будет работать с нашим уже настроеным xdebug сервером.
Переходим вот сюда

Screenshot_10

Создаем новый Web Application

Screenshot_11

Указываем все требуемые параметры согласно скриншота

Нажимаем Apply и OK. После чего у нас появится вот такой тулбар

Screenshot_12

Screenshot_13

Ставим брейкпойнт в index.php Magento

Screenshot_14

Пробуем начать отладку. Нажимаем на зеленого жука в нашем тулбаре в правом верхнем углу
Видим следующее

Screenshot_16

Нажимаем ОК и снова запускаем сессию xdebug и ВУАЛЯ! Все работает.

Вот таким образом можно настроить xdebug для того чтобы была возможность заниматься отладкой кода используя интерпритатор гостевой машины и установленый там отладчик.
На этом все, если у Вас возникнут сложности, трудности или будет остутствовать понимание того, что вы делаете , не стеснятесь писать в комментариях и задавать вопросы. Будем вместе с Вами разбираться и настраивать ваше окружение. Спасибо за внимание.

Читайте также: