Xdebug helper chrome настройка
Xdebug provides an interface for debugger clients that interact with running PHP scripts. This section explains how to set-up PHP and Xdebug to allow this, and introduces a few clients.
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:
RUN pecl install xdebug \ && docker-php-ext-enable xdebug && echo "xdebug.mode=debug" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \ && echo "xdebug.client_host = host.docker.internal" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
In this example, we're modifying /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini providing the mode and client_host Xdebug parameters.
Note that the xdebug.client_host value should be replaced with the IP address of the machine where PhpStorm is running, which is accessible from the Docker container. If you are using Docker for Windows or Docker for Mac, you can set xdebug.client_host to host.docker.internal , which automatically resolves to the internal address of the host, letting you easily connect to it from the container.
RUN pecl install xdebug \ && docker-php-ext-enable xdebug && echo "xdebug.remote_enable=on" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini \ && echo "xdebug.remote_host = host.docker.internal" >> /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
In this example, we're modifying /usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini providing the remote_enable and remote_host Xdebug parameters.
Note that the xdebug.remote_host value should be replaced with the IP address of the machine where PhpStorm is running, which is accessible from the Docker container. If you are using Docker for Windows or Docker for Mac, you can set xdebug.remote_host to host.docker.internal , which automatically resolves to the internal address of the host, letting you easily connect to it from the container.
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:
To enable Xdebug, locate or create the [xdebug] section in the php.ini file and update it as follows:
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:
Introduction
Xdebug's (remote) debugger allows you to examine data structure, interactively walk through your and debug your code. The protocol that is being used is open, and is called DBGp. This protocol is implemented in Xdebug 2, and replaces an older GDB-like protocol that is no longer supported.
Implementation Details
Xdebug's implementation of the DBGp protocol's context_names command does not depend on the stack level. The returned value is always the same during each debugger session, and hence, can be safely cached.
Using a GET parameter
If you want to debug a script started through a web browser, simply add XDEBUG_SESSION_START=session_name as parameter to the URL. Instead of using a GET parameter, you can also set XDEBUG_SESSION_START as a POST parameter, or through a cookie named XDEBUG_SESSION. Refer to the next section to read on how debug sessions work from within a browser window.
Settings
Available in Xdebug
Controls whether Xdebug should enforce 'extended_info' mode for the PHP parser; this allows Xdebug to do file/line breakpoints with the remote debugger. When tracing or profiling scripts you generally want to turn off this option as PHP's generated oparrays will increase with about a third of the size slowing down your scripts. This setting can not be set in your scripts with ini_set(), but only in php.ini.
Controls which IDE Key Xdebug should pass on to the debugging client or proxy. The IDE Key is only important for use with the DBGp Proxy Tool, although some IDEs are incorrectly picky as to what its value is.
The default is based on the DBGP_IDEKEY environment setting. If it is not present, the default falls back to an empty string.
If this setting is set to a non-empty string, it selects its value over DBGP_IDEKEY environment variable as default value.
The internal IDE Key also gets updated through debugging session management and overrides the value of this setting as is explained in the documentation.
Introduced in Xdebug >= 2.4
If xdebug.remote_addr_header is configured to be a non-empty string, then the value is used as key in the $SERVER superglobal array to determine which header to use to find the IP address or hostname to use for 'connecting back to'. This setting is only used in combination with xdebug.remote_connect_back and is otherwise ignored.
Introduced in Xdebug >= 2.1
This setting does not apply for debugging through the CLI, as the $SERVER header variables are not available there.
Please note that there is no filter available, and anybody who can connect to the webserver will then be able to start a debugging session, even if their address does not match xdebug.remote_host.
Introduced in Xdebug >= 2.1
This setting can be used to increase (or decrease) the time that the remote debugging session stays alive via the session cookie.
This switch controls whether Xdebug should try to contact a debug client which is listening on the host and port as set with the settings xdebug.remote_host and xdebug.remote_port. If a connection can not be established the script will just continue as if this setting was 0.
Available in Xdebug
Can only be 'dbgp' to represent the debugger protocol. The DBGp protocol is the only supported protocol.
Selects the host where the debug client is running, you can either use a host name, IP address, or 'unix:///path/to/sock' for a Unix domain socket. This setting is ignored if xdebug.remote_connect_back is enabled.
Support for Unix domain sockets was introduced in Xdebug 2.6.
Configures a file name to log all Step Debugging connection attempts, failures, and communication.
Enable this functionality by setting the value to a absolute path. Make sure that the system user that PHP runs at (such as www-data if you are running with Apache) can create and write to the file.
The file is opened in append-mode, and will therefore not be overwritten by default. There is no concurrency protection available.
When successfully enabled, the log file will include any attempt that Xdebug makes to connect to an IDE:
It includes the opening time ( 2020-06-21 17:54:05 ), the IP/Hostname and port Xdebug is trying to connect to ( localhost:9000 ), and whether it succeeded ( Connected to client :-) ). The number in brackets ( [1603325] ) is the Process ID.
It also logs the debugging communication itself, which starts with the
The fileuri attribute lists the entry point of your application, which can be useful to compare to breakpoint_set commands to see if path mappings are set-up correctly.
You can read about DBGP - A common debugger protocol specification at its dedicated documation page.
The xdebug.remote_log_level setting controls how much information is logged.
Note: Many Linux distributions now use systemd, which implements private tmp directories. This means that when PHP is run through a web server or as PHP-FPM, the /tmp directory is prefixed with something akin to:
Introduced in Xdebug >= 2.8
Configures which logging messages should be emitted by the Step Debugging.
The following levels are supported:
Level | Name | Example |
---|---|---|
1 | Errors | Connection errors |
3 | Warnings | Connection warnings |
5 | Communication | Protocol messages |
7 | Information | Information while connecting |
10 | Debug | Breakpoint resolving information |
Selects when a debug connection is initiated. This setting can have two different values:
req Xdebug will try to connect to the debug client as soon as the script starts. jit Xdebug will only try to connect to the debug client as soon as an error condition occurs.
The port to which Xdebug tries to connect on the remote host. Port 9000 is the default for both Xdebug and the Command Line Debug Client. As many clients use this port number, it is best to leave this setting unchanged.
Introduced in Xdebug >= 2.6
The amount of time in milliseconds that Xdebug will wait for on an IDE to acknowledge an incoming debugging connection. The default value of 200 ms should in most cases be enough. In case you often get dropped debugging requests, perhaps because you have a high latency network, or a development box far away from your IDE, or have a slow firewall, then you can should increase this value.
Please note that increasing this value might mean that your requests seem to 'hang' in case Xdebug tries to establish a connection, but your IDE is not listening.
Configure Xdebug running on a Vagrant instance
To configure Xdebug running on a Vagrant instance, connect to the Vagrant machine and provide the Xdebug-specific parameters in the php.ini file:
Note that the xdebug.client_host value is 10.0.2.2 . This is the gateway used in the default Vagrant setup, which allows connecting from the instance to host where PhpStorm is running.
[xdebug] zend_extension="
Note that the xdebug.remote_host value is 10.0.2.2 . This is the gateway used in the default Vagrant setup, which allows connecting from the instance to host where PhpStorm is running.
Configure Xdebug running in a WSL instance
To configure Xdebug running in a WSL environment, connect to the WSL Linux installation and provide the Xdebug-specific parameters in the php.ini file:
Note that the xdebug.client_host value has to be set to the IP address of the WSL host machine. To obtain it, run the following command inside the WSL Linux installation:
Note that the xdebug.remote_host value has to be set to the IP address of the WSL host machine. To obtain it, run the following command inside the WSL Linux installation:
If you use Docker Compose inside a WSL environment, do the following to obtain the correct WSL host IP address.
Connect to the WSL Linux installation and set an environment variable for the IP address of the WSL host machine in a .bashrc or .zshrc file.
Pass this environment variable to the extra_hosts parameter for the php service in the docker-compose.yml file.
В этом уроке мы проведем полную настройку дебаггера для PHP8 в связке с PhpStorm. Для PHP7 используйте инструкцию по настройке XDebug для PHP7.
Отладка программы – это процесс, в ходе которого обнаруживают и устраняют баги. Для этого нам нужно знать, например, значения переменных на каждом шаге выполнения программы, или смотреть выполнилось ли условие, или даже погружаться в работу рекурсивных функций.
Собственно, так как многим рекурсия показалась сложной, то я решил сделать урок по отладке кода на PHP 8. В этой статье мы рассмотрим настройку отладки с помощью PHP-расширения Xdebug, а производить отладку мы будем в уже известной нам IDE PHPStorm.
Зачем вообще нужен Xdebug когда есть современные IDE и Blackfire?
Современные IDE предоставляют широкие возможности поиска по коду, так что полезность функционала форматирования ссылок кажется сомнительной. Существуют всевозможные системы логирования способные обрабатывать ошибки и исключения. Также, трассировка и профилирование функций прекрасно реализованы в Blackfire. Не смотря на все это, форматирование ссылок на файлы лишь одна из функций Xdebug, а использование Blackfire связано с собственными трудностями — установка расширения, настройка горячих клавиш, и оплата сохранения истории трассировок. А использование логгеров требует внимательности, так как добавить их в приложение на поздних этапах не самая простая задача.
Но область использования Xdebug не ограничивается лишь этим. Он всё ещё необходим для правильного модульного тестирования (тестируемые фреймворки зависимы от его отчетов о покрытии кода), далеко не так легко провести отладку через удаленные брейк-пойнты другими средствами, а этот инструмент настолько старый и стабильный, что был отшлифован почти до идеала.
Конечно, нет никакой необходимости использовать Xdebug, если ваш текущий инструментарий может обеспечить всё что он предоставляет, или если вам не нужны его возможности, однако у меня не было еще ни одного проекта который можно было бы завершить так же эффективно без его использования.
Starting The Debugger
In order to enable Xdebug's debugger you need to make some configuration settings in php.ini. These settings are xdebug.remote_enable to enable the debugger, xdebug.remote_host and xdebug.remote_port to configure the IP address and port where the debugger should connect to. There is also a xdebug.remote_connect_back setting that can be used if your development server is shared with multiple developers.
If you want the debugger to initiate a session when an error situation occurs (PHP error or exception) then you also need to change the xdebug.remote_mode setting. Allowed values for this setting are "req" (the default) which makes the debugger initiate a session as soon as a script is started, or "jit" when a session should only be initiated on an error.
After made all those settings Xdebug will still not start a debugging session automatically when a script is run. You need to activate Xdebug's debugger and you can do that in three ways:
Functions
Emits a breakpoint to the debug client
This function makes the debugger break on the line it is called from, as if a normal file/line breakpoint was set on this line through the debugger protocol.
The function returns true if a debugging session is (now) active, and the breakpoint was succesfully set. It returns false if a debugging session was not active and could not be activated.
Returns whether a debugging session is active
Returns true if a debugging session through DBGp is currently active with a client attached; false , if not.
This site and all of its contents are Copyright © 2002-2020 by Derick Rethans.
All rights reserved.
Xdebug поставляется с подробной инструкцией по установке в которой учтены практически все возможные варианты использования, хотя, если вы хотите поэкспериментировать с представленным ниже функционалом, мы рекомендуем использовать Homestead Improved так как там Xdebug установлен и активирован по умолчанию.
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.
Type xdebug.start_upon_error in the Configuration directive field and yes in the Value field.
Type xdebug.remote_mode in the Configuration directive field and jit 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).
Using a browser extension
Before you start your script you will need to tell your client that it can receive debug connections, please refer to the documentation of the specific client on how to do this. To use the bundled client simply start it after downloading it. You can start it by running dbgpClient on Linux, dbgpClient-macos on MacOS, and dbgpClient.exe on Windows.
When the debug client starts it will show version information and then waits until a connection is initiated by the debug server (Xdebug):
After a connection is made the output of the debug server is shown:
Now you can use the commands as explained on the DBGp documentation page. When the script ends the debug server disconnects from the client and the debug client resumes with waiting for a new connection. There is a more comprehensive documentation available for Command Line Debug Client as well.
Clients
- Eclipse plugin (IDE).
- KDevelop (IDE: Linux (KDE); Open Source).
- ActiveState's Komodo (IDE: Windows, Linux, Mac; Commercial).
- NetBeans (IDE: Windows, Linux, Mac OS X and Solaris).
- Notepad++plugin (Editor: Windows).
- Devsense's PHP Tools for Visual Studio (MS Visual Studio Plugin; Commercial).
- JetBrain's PhpStorm (IDE; Commercial).
- pugdebug (Standalone client for Linux, Windows and Mac OS X; Open Source).
- SublimeTextXdebug (Plugin for Sublime Text 2 and 3, Open Source).
- VIM plugin (Editor Plugin).
The simple command line client dbgpClient for debugging is available on the download page.
Custom DBGp commands
The DBGp protocol allows for debugger engine specific commands, prefixed with the xcmd_ prefix. Xdebug includes a few of these, and they're documented here.
Начинаем отлаживать
Итак, все настройки выполнены и дело осталось за малым – начать пользоваться отладчиком.
Вернёмся снова в IDE, в нашем index.php запишем следующий код:
А затем слева от строки $x *= 2; кликнем по пространству между номером строки и самим кодом – появится красная точка.
Это брэйкпоинт (breakpoint), или, как её ещё называют – точка останова. К ней мы вернёмся чуть позже.
В правом верхнем углу PhpStorm напротив выбранной конфигурации XDebug нажимаем на значок зеленого жучка. На нём загорится точка. Внизу IDE появится консоль.
Нажмем правой кнопкой мыши на вкладке Console и уберем галочку "Focus on startup".
И переходим во вкладку Debugger.
Теперь возвращаемся во вкладку браузера с нашим открытым проектом, жмём на иконку плагина Xdebug helper (жучок), выбираем пункт Debug.
После чего значок станет зелёным.
Теперь можно в Chrome обновить страницу, и увидеть, что она повисла в режиме загрузки.
А в окне PHPStorm увидеть следующее:
Наша программа остановила своё выполнение в месте брэйкпоинта.
Внизу программы (во вкладке Variables) мы можем видеть значения всех переменных в данный момент. Как видим, сейчас (до выполнения строки 5) $x равна 7.
Давайте нажмём кнопку “F8”. Она осуществляет выполнение кода на текущей строке и останавливается перед следующим действием.
Умножили $x на 2, и как видим, её значение стало равно 14. Вот так с помощью отладки мы можем отслеживать значения переменных в какой-то определенный момент работы программы.
Помимо этого, есть, разумеется, и другие сочетания клавиш, которые используются во время отладки.
Давайте прямо сейчас нажмём F9. Это приведет к тому, что программа продолжит выполнение до следующего брэйкпоинта (да, их можно наставить сколько угодно). Если их больше не встретится (как в нашем примере), то программа просто завершит свою работу.
Давайте поиграемся с кодом посложнее:
И установим два брэйкпоинта на строках 5 и 10.
После чего обновим нашу страничку в браузере и попадём в первый брэйкпоинт на строке 10:
Здесь мы видим значения переменных $x и $y внутри функции. Нажмём F9 и программа выполнится до того момента, пока не дойдёт до следующего брэйкпоинта.
Здесь мы уже видим, что внутри функции доступны переменные $x и $y. Но это уже другие переменные, не те, что были переданы в функцию getSumOfCos(). Вот мы и увидели локальную область видимости в действии.
Помимо этого, в левом нижнем углу есть окошечко “Frames”, это так назваемый “стек вызовов”. Здесь мы можем переключаться на места, откуда был вызван наш код ранее. Так мы можем переключиться в то место, где была вызвана функция getSum().
И можем посмотреть переменные, которые были доступны в той области видимости (уровнем выше).
Ещё в правом нижнем углу можно увидеть окошечко “Watches”. Это такое место, где можно задать переменные или даже выражения, значения для которых вы хотели бы видеть всегда под рукой. Добавляются они туда с помощью плюсика. В появившемся окошечке вводим выражение, которое мы бы хотели отслеживать. Пусть это будет $x/2.
Отлично, осталось рассмотреть ещё одну клавишу и вы готовы к бою – F7. Она позволяет зайти “внутрь” какой-либо конструкции.
Давайте закончим отладку нажатием F9. Поставим теперь только один брэйкпоинт на строке номер 15 и обновим страничку в браузере.
Если сейчас нажать F8, то программа закончит своё выполнение, и мы не попадём внутрь функций. Так происходит потому что во время отладки мы работаем на определённых уровнях вложенности, и если нам нужно будет попасть внутрь функции, то нужно будет нажать F7, находясь на строке 15. После этого мы окажемся на строке 10. Если сейчас нажать F8, попадём на строку 11. Ещё раз – на строку 12. Если мы сейчас, находясь на 12 строке нажмем F7, то попадём внутрь функции getSum() на строку 5. А если бы мы нажали F8, то мы просто поднялись бы на уровень выше, в то место, где была вызвана функция getSumOfCos().
В принципе, большего для отладки вам не потребуется (лично мне этого хватает).
Ну а сейчас пришла пора поотлаживать рекурсивные функции. Коль уж у вас возникли проблемы с прошлой домашкой – давайте их решать =)
Давайте возьмем и поковыряем код из предыдущей домашки:
Поставим брэйкпоинт на 3 строке и запустим программу.
Итак, в функцию попала переменная $x = 3. Нажимаем F8, и попадаем на строку 7, так как условие не выполнилось. Теперь нажмём F7 и снова попадём в начало нашей функции, но теперь $x = 2. И при этом стек вызовов увеличился ещё на одну строку, то есть мы вошли в ещё один уровень вложенности.
Жмём F8 и снова оказываемся на строке 7. Нажимаем F7 и снова попадаем в новый вызов функции, только уже $x = 1, а в стэке вызовов появился ещё один уровень.
Снова F8 и затем F7. И вот уже в функции $x = 0.
Жмём F8 и оказываемся на строке 4 (теперь условие выполнилось). На этой строке программа выведет 0.
Жмём F8 и попадаем на строку 5. Сейчас функция завершит свою работу и мы попадём на уровень выше, в то место, где она была вызвана. Итак, жмём F8.
Вуаля, мы вернулись на уровень выше, там, где переменная $x = 1.
И попали мы на следующую строку, после той в которой вызвали функцию numbers(1 - 1). И на этой строке мы вывели уже число 1. А дальше – жмите F8 и наблюдайте за ходом выполнения программы. Надеюсь теперь рекурсия для вас понятна =)
Принудительное отображение Xdebug в Laravel
По умолчанию, Laravel имеет собственные отчеты об ошибках и настройки рендеринга. Ошибка, вроде той что мы вызвали ранее с неопределенной переменной, в Laravel будет выглядеть так:
Хотя экран ошибок Symfony (который Laravel использует в этом случае) способен так же хорошо работать с переходами Xdebug (попробуйте! Вы можете кликнуть по этим файлам и их строкам!), мне очень не хватает вывода информации о памяти (Xdebug по умолчанию выводит отчет об использовании памяти в каждый момент времени в трассировке). Давайте вернемся к экрану Xdebug в режиме разработки, чтобы отследить этот параметр.
Как видите мы обновили наш роутинг по умолчанию таким образом, чтобы сначала он активировал отображение ошибок (экран который мы видели ранее не показывает ошибки сразу при появлении, а сохраняет в стек исключений который был позже извлечен и визуализирован), затем мы возвращаем обработчик ошибок в его значение по умолчанию переопределяя значение Laravel.
После обновления, конечно же, вернулся наш старый экран — просто взгляните на эту простыню трассировки стэка и потребления памяти.
Я советую вам продолжить дальнейшее изучение самостоятельно — просмотрите документацию, поиграйте с настройками, выясните сколько всего вы можете узнать о ваших приложениях.
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: 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.
Отключение Xdebug
После чего нужно перезапустить PHP-FRM:
Примечание: если вы используете среду разработки с другой версией PHP, файл настроек вашего Xdebug скорее всего будет в другом месте. Сверьтесь с документацией системы чтобы найти его или задайте вопрос в комментариях.
Выглядит довольно скудно, не так ли? Из вывода пропал весь стек вызовов. Конечно, пока эта информация не слишком полезна, так как мы работаем только с одной строкой в единственном файле, но позже мы будем использовать ее довольно часто.
Теперь вновь активируем Xdebug, раскомментировав строку в отредактированном ранее файле, и продолжим. Не забудьте перезапустить PHP!
Использование профайлера.
В конце давайте рассмотрим одну из часто игнорируемых функций: профайлер. Для этого нам понадобится какое-нибудь крупное приложение, например Laravel:
И снова нам нужно внести правки в файл 20-xdebug.ini, добавив следующее:
Заметьте — мы не используем xdebug.profiler_enable = 1, так как не хотим чтобы он оставался включенным всё время. Вместо этого мы используем триггерный параметр в запросе “XDEBUG_PROFILE” для выборочной активации. Также мы выводим профиль кэша в основную общую папку нашей виртуальной машины, получая возможность работать с ним в операционной системе хоста.
После перезапуска PHP мы можем проверить это выполнив homestead.app/?XDEBUG_PROFILE (замените homestead.app на имя выбранного вами виртуального хоста или IP-адрес виртуальной машины). Конечно же, файл там где и ожидалось:
В каждой операционной системе есть собственный инспектор кэширования, для OS X, например, можно использовать qcachegring, который легко устанавливается через Homebrew. После установки…
… и открытия файла, мы видим удобное разбиение потока выполнения:
Профайлер предоставляет детализированный доступ ко многим данным и возможность досконально изучить поведение вашего кода, также как и в Blackfire. Однако с локальным выводом профайлера намного легче автоматизировать непрерывное отслеживание производительности и сложности выполнения.
Заключение
Xdebug — ценный инструмент в наборе любого разработчика. Это мощное расширение полностью соответствует своему названию, делая язык, с которым мы ежедневно работаем, более подробным, дружелюбным и менее загадочным при возникновении ошибок.
За 15 лет своего существования Xdebug установил высокие стандарты для отладочных средств. Я хотел бы поблагодарить Дерика за разработку и поддержку всё это время, и буду рад если вы решите написать одно-два руководства об углубленном использовании, подводных камнях или скрытых комбинациях функций о которых никто не задумывался прежде. Давайте поможем его распространению и развитию и в следующие 15 лет.
Каждый разработчик время от времени сталкивается с непонятными ошибками. Как правило, их причина неочевидна и чтобы их пофиксить, нужно детально понять, что происходит в коде. Модуль xdebug — инструмент для профессионального поиска ошибок. Когда выполнение кода доходит до точки останова, xdebug присоединяется к IDE, которая слушает порт (по умолчанию 9000). Эта схема хорошо работает на localhost. Если вы находитесь в прямой видимости удаленного сервера, то можно прописать в конфиге xdebug ваш ip, и производить отладку аналогично. Но если компьютер разработчика находится за NAT, то прямой доступ с сервера к нему невозможен.
Я давно использую xdebug на localhost, но, разобравшись с port forwarding, научился отлаживать на удаленном сервере и решил написать инструкцию, которая может быть полезной каждому разработчику, а главное — она работает.
В качестве IDE я использовал PhpStorm, браузер Chrome, ОС Ubuntu. Port forwarding без проблем работает и в windows.
Настройки сервера
Опция xdebug.idekey может быть PhpStorm1, netbeans-xdebug, XDEBUG_ECLIPSE, в зависимости от IDE, или пустым.
В итоге вывод phpinfo() должен содержать информацию о xdebug:
Настройки клиента
Chrome Xdebug helper
Если планируется использовать idekey, то для Chrome нужно поставить Xdebug helper.
В настройках расширения параметр IDE key нужно указать PhpStorm1 и в Domain filter вписать host. При отладке в адресной строке нужно нажимать Debugging Enabled.
Настройка PhpStorm
File -> Settings -> xdebug. Port 9000. На панели Edit debug configuration -> Add New Configuration -> PHP Web Application
Нужно указать Name, Start URL, создать новый сервер. У сервера указать Name, Host, Port, path mapping. Сохранить все.
Теперь можно поставить точку останова и нажать на кнопку debug, чтобы IDE начала слушать порт. Запустится браузер со страницей Server + Start URL, а в параметре будет XDEBUG_SESSION_START, который определяет идентификатор сессии. Не теряйте его при отладке.
Port forwarding
Xdebug стучится в порт, который слушает IDE. Если мы хотим отлаживать удаленный сервер и сидим за NATом, то наши порты недоступны. Оптимальный вариант — перенаправление удаленного порта на локальный с помощью ssh. Для работы под windows нужно установить Cygwin с пакетом ssh.
Проверка port forwarding
Нужно попробовать установить связь на удаленной машине на ее 9000 порт. Если все сделано правильно, то соединение будет установлено, по факту, с нашим локальным портом.
Успешеный коннект:
Горячая клавиша выхода из telnet сессии — Ctrl + ].
Возможные ошибки:
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.
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.start_upon_error from the default default to yes .
Change the value of the xdebug.remote_mode from the default req to jit .
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:
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 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 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.
Настройка отладки в PHPStorm
Теперь нам нужно настроить отладку в PhpStorm. Первым делом идём в настройки:
File -> Settings
Здесь в левом меню выбираем:
PHP -> Debug
В секции Xdebug задаём следующие настройки:
- Debug port: 9003
- Force break at first line when no path mapping specified: выключено
- Force break at first line when a script is outside the project: выключено
Теперь в верхнем правом углу PhpStorm находим кнопку Add configuration
В появившемся окне жмем на плюсик и выбираем пункт PHP Remote Debug.
В поле Name пишем XDebug.
Ставим галочку напротив пункта "Filter debug connection by IDE key". В поле IDE key пишем "PHPSTORM". Напротив пункта Server нажимаем на три точки. При помощи плюсика добавляем новый сервер. Заполняем поля как на скриншоте ниже:
Жмём ОК и выбираем только что добавленный сервер. Должно получиться так:
После чего снова жмём ОК.
With an unknown IP/multiple developers
If xdebug.remote_connect_back is used, the set-up is slightly different:
- When the URL variable XDEBUG_SESSION_START=name is appended to an URL—or through a POST variable with the same name—Xdebug emits a cookie with the name "XDEBUG_SESSION" and as value the value of the XDEBUG_SESSION_START URL parameter. The default expiry time of the cookie is one hour, but this can be configured through the xdebug.remote_cookie_expire_time setting. The DBGp protocol also passes this same value to the init packet when connecting to the debugging client in the "idekey" attribute.
- When there is a GET (or POST) variable XDEBUG_SESSION_START or the XDEBUG_SESSION cookie is set, Xdebug will try to connect to a debugging client.
- To stop a debug session (and to destroy the cookie) simply add the URL parameter XDEBUG_SESSION_STOP . Xdebug will then no longer try to make a connection to the debugging client.
Multiple Users Debugging
Xdebug only allows you to specify one IP address to connect to with xdebug.remote_host) while doing remote debugging. It does not automatically connect back to the IP address of the machine the browser runs on, unless you use xdebug.remote_connect_back.
If all of your developers work on different projects on the same (development) server, you can make the xdebug.remote_host setting for each directory through Apache's .htaccess functionality by using php_value xdebug.remote_host=10.0.0.5 . However, for the case where multiple developers work on the same code, the .htaccess trick does not work as the directory in which the code lives is the same.
There are two solutions to this. First of all, you can use a DBGp proxy. For an overview on how to use this proxy, please refer to the article at Debugging with multiple users. You can download the proxy on ActiveState's web site as part of the python remote debugging package. There is some more documentation in the Komodo FAQ.
Secondly you can use the xdebug.remote_connect_back setting that was introduced in Xdebug 2.1.
Переходы по файлам
Если у вас есть любимая IDE (у меня, например, PhpStorm), возможность переходить к файлам в ней простым кликом в трассировке стека была бы определенно полезной и значительно увеличила бы скорость отладки. Я продемонстрирую как реализовать эту возможность для PhpStorm.
Давайте снова откроем файл 20-xdebug.ini и добавим в него следующее:
Заметьте, что не во всех браузерах это будет работать. Например, у Opera возникнут проблемы со ссылкой phpstorm:// и она радостно упадет, в то время как Firefox и Chrome прекрасно обрабатывают такие ссылки.
Если теперь обновить нашу PHP страницу с ошибкой, мы получим ссылки открывающие IDE сразу в точном местоположении ошибки:
Настройка для работы с другими IDE и редакторами происходит точно так же.
Настройка отладки PHP 8 в OpenServer
Первым делом нужно включить расширение Xdebug в файле конфигурации PHP (php.ini). Для этого идём в меню
OpenServer -> Дополнительно -> Конфигурация -> PHP8.
И раскомментируйте её, убрав ; в начале строки, чтобы получилось вот так:
Затем находим секцию [xdebug]
Здесь нам нужно раскомментировать/изменить значения параметров на следующие:
После этого сохраните файл (CTRL + S) и перезапустите веб-сервер.
На этом настройка веб-сервера для отладки завершена.
Communication Set-up
DBGp: xcmd_get_executable_lines
This command returns which lines in an active stack frame can have a working breakpoint. These are the lines which have an EXT_STMT opcode on them. This commands accepts a -d option, which indicates the stack depth, with 0 being the top leve stack frame.
The command returns the information in the following XML format:
Related Settings and Functions
- integer xdebug.extended_info = 1
- string xdebug.idekey = *complex*
- string xdebug.remote_addr_header = ""
- boolean xdebug.remote_autostart = false
- boolean xdebug.remote_connect_back = false
- integer xdebug.remote_cookie_expire_time = 3600
- boolean xdebug.remote_enable = false
- string xdebug.remote_handler = dbgp
- string xdebug.remote_host = localhost
- string xdebug.remote_log =
- integer xdebug.remote_log_level = 7
- string xdebug.remote_mode = req
- integer xdebug.remote_port = 9000
- integer xdebug.remote_timeout = 200
-
() : bool () : bool
DBGp: xcmd_profiler_name_get
If Xdebug's profiler is currently active (See: Profiling), this command returns the name of the file that is being used to write the profiling information to.
With a static IP/single developer
With remote debugging, Xdebug embedded in PHP acts like the client, and the IDE as the server. The following animation shows how the communication channel is set-up:
Xdebug, Vagrant и PhpStorm
Зачем останавливаться на этом? Многие сегодня используют для разработки виртуальные машины, позволяющие быть уверенным в том что никакая часть из среды исполнения PHP не затронет основную машину, при этом сохраняя всё быстрым и гладким. Как ведет себя Xdebug в таких случаях? Кроме того, возможно ли, в принципе, выполнять отладку с брейк-поинтами, когда вы проходите по своему коду и проверяете каждую строку отдельно?
К счастью, Xdebug отлично поддерживает использование брейк-пойнтов при удаленном соединении. Мы рассмотрели этот процесс выше, а полностью иллюстрированное руководство по настройке вы можете найти в этой статье.
Настройка расширения Xdebug helper
Далее заходим в магазин расширений Google Chrome, находим расширение XDebug helper и устанавливаем его.
В правом верхнем углу Google Chrome находим иконку с паззлом, жмем на нее, и напротив XDebug helper жмём на три точки. Выбираем пункт "Параметры".
В секции IDE key выбираем PhpStorm и обязательно! жмём кнопку Save.
Жмём на паззл ещё раз, и напротив пункта Xdebug helper жмём кнопку для закрепления плагина на панели.
Using an environment variable
When running the script from the command line you need to set an environment variable, like:
On Windows, setting an environment variable is done with set :
You can also configure the xdebug.remote_host, xdebug.remote_port, xdebug.remote_mode and xdebug.remote_handler in this same environment variable as long as you separate the values by a space:
All settings that you can set through the XDEBUG_CONFIG setting can also be set with normal php.ini settings.
Давайте попробуем
Предполагается что на этом этапе у вас уже есть среда с работающим Xdebug. Если нет, попробуйте воспользоваться Homestead Improved.
Давайте создадим новый проект состоящий из одного файла index.php и выведем несуществующую переменную $foo:
Вот что мы получим:
Читайте также: