Installation
For packages that have the PHP version in the package name, such as in php81-php-xdebug3 , you can substitute the PHP version with the one that matches the PHP version that you are running.
Installing with PECL #
You can install Xdebug through PECL on Linux & macOS with Homebrew.
- macOS:
- Xcode’s command line tools (run: xcode-select —install ).
- PHP installed through Homebrew.
- GCC and associated libraries.
- PHP development headers (see Compile below).
pecl install xdebug
You should ignore any prompts to add «extension=xdebug.so» to php.ini — this will cause problems.
In some cases pecl will change the php.ini file to add a configuration line to load Xdebug. You can check whether it did by running php -v . If Xdebug shows up with a version number, than you’re all set and you can configure Xdebug’s other functions, such as Step Debugging, or Profiling.
If it is there, you can skip to the What’s Next? section.
Issues on macOS #
On Apple M1 hardware, programs can either be compiled for the native M1/ARM64 architecture, or for the emulated x86_64 architecure. Sometimes there is a mismatch with the default and PECL will fail, or Xdebug won’t load with a message such as:
PHP Warning: Failed loading Zend extension 'xdebug.so' (tried: /opt/homebrew/lib/php/pecl/20190902/xdebug.so (dlopen(/opt/homebrew/lib/php/pecl/20190902/xdebug.so, 9): no suitable image found. Did find: /opt/homebrew/lib/php/pecl/20190902/xdebug.so: mach-o, but wrong architecture /opt/homebrew/lib/php/pecl/20190902/xdebug.so: stat() failed with errno=22), /opt/homebrew/lib/php/pecl/20190902/xdebug.so.so (dlopen(/opt/homebrew/lib/php/pecl/20190902/xdebug.so.so, 9): image not found)) in Unknown on line 0
You can verify what your PHP’s architecture is with:
file `which php`
If that says arm64e , then you need to run:
arch -arm64 sudo pecl install xdebug
And if it’s x86_64 , then you need to run:
arch -x86_64 sudo pecl install xdebug
1 On macOS, you should have PHP installed with Homebrew.
Installing on Windows #
There are a few precompiled modules for Windows, they are all for the non-debug version of PHP. You can get those at the download page. Follow these instructions to get Xdebug installed.
Installation From Source #
Obtain #
You can download the source of the latest stable release 3.2.2.
Alternatively you can obtain Xdebug from GIT:
git clone git://github.com/xdebug/xdebug.git
This will checkout the latest development version which is currently 3.2.0dev. This development branch might not always work as expected, and may have bugs.
Compile #
There is a wizard available that provides you with the correct file to download, and which paths to use.
You compile Xdebug separately from the rest of PHP. You need access to the scripts phpize and php-config . If your system does not have phpize and php-config , you will need to install the PHP development headers.
Debian users can do that with:
apt-get install php-dev
And RedHat and Fedora users with:
yum install php-devel
It is important that the source version matches the installed version as there are slight, but important, differences between PHP versions. Once you have access to phpize and php-config , take the following steps:
- If you downloaded a tarball, unpack it: tar -xzf xdebug-3.2.2.tgz You should not unpack the tarball inside the PHP source code tree. Xdebug is compiled separately, all by itself, as stated above.
- Change into the source directory:
- tarball: cd xdebug-3.2.2
- GIT clone: cd xdebug
Configure PHP #
- Find out which PHP ini file to modify. Run a script with the following to find all configuration files that PHP has loaded:
PHP 7.4.10 (cli) (built: Aug 18 2020 09:37:14) ( NTS DEBUG ) Copyright (c) The PHP Group Zend Engine v3.4.0, Copyright (c) Zend Technologies with Zend OPcache v7.4.10-dev, Copyright (c), by Zend Technologies with Xdebug v3.0.0-dev, Copyright (c) 2002-2020, by Derick Rethans
What’s Next? #
With Xdebug loaded, you can now enable individual features, such as Step Debugging, or Profiling. Information on what these featers are, how they work, and how to configure them is available on each feature’s documentation page:
- Step Debugging — Analyse PHP code while it runs
- Profiling — Check your application for performance issues
- Function Trace — Show every function call, assignment, and return value
- Code Coverage Analysis — Analyse whether your tests cover your whole code base
Related Content #
- Activation and Triggers This video explains how to activate, through triggers and other method’s Xdebug’s step debugger, profiler, and tracer.
- Xdebug 3: Diagnostics This video teaches you how to troubleshoot your Xdebug setup. It explains how to find out how Xdebug is configured, which settings have been made, and what it is attempting to do regarding its different features.
- Xdebug 3: Modes This video introduces Xdebug 3’s modes — the new way to configure which parts of Xdebug you have enabled.
Related Settings and Functions #
- string xdebug.log =
- integer xdebug.log_level = 7
- string xdebug.mode = develop
- xdebug_info () : mixed
Settings #
string xdebug.log = #
Configures Xdebug’s log file.
Xdebug will log to this file all file creations issues, Step Debugging connection attempts, failures, and debug 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.
The log file will include any attempt that Xdebug makes to connect to an IDE:
[2693358] Log opened at 2020-09-02 07:19:09.616195 [2693358] [Step Debug] INFO: Connecting to configured address/port: localhost:9003. [2693358] [Step Debug] ERR: Could not connect to debugging client. Tried: localhost:9003 (through xdebug.client_host/xdebug.client_port). [2693358] [Profiler] ERR: File '/foo/cachegrind.out.2693358' could not be opened. [2693358] [Profiler] WARN: /foo: No such file or directory [2693358] [Tracing] ERR: File '/foo/trace.1485761369' could not be opened. [2693358] [Tracing] WARN: /foo: No such file or directory [2693358] Log closed at 2020-09-02 07:19:09.617510
It includes the opening time ( 2020-09-02 07:19:09.616195 ), the IP/Hostname and port Xdebug is trying to connect to ( localhost:9003 ), and whether it succeeded ( Connected to client ). The number in brackets ( [2693358] ) is the Process ID.
It includes: [2693358] process ID in brackets 2020-09-02 07:19:09.616195 opening time
INFO: Connecting to configured address/port: localhost:9003. ERR: Could not connect to debugging client. Tried: localhost:9003 (through xdebug.client_host/xdebug.client_port).
ERR: File '/foo/cachegrind.out.2693358' could not be opened. WARN: /foo: No such file or directory
ERR: File '/foo/trace.1485761369' could not be opened. WARN: /foo: No such file or directory
Step Debugger Communication
The debugging log can also log the communication between Xdebug and an IDE. This communication is in XML, and 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.log_level setting controls how much information is logged.
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:
/tmp/systemd-private-ea3cfa882b4e478993e1994033fc5feb-apache.service-FfWZRg
This setting can additionally be configured through the XDEBUG_CONFIG environment variable.
integer xdebug.log_level = 7 #
Configures which logging messages should be added to the log file.
The log file is configured with the xdebug.log setting.
The following levels are supported:
Level Name Example 0 Criticals Errors in the configuration 1 Errors Connection errors 3 Warnings Connection warnings 5 Communication Protocol messages 7 Information Information while connecting 10 Debug Breakpoint resolving information Criticals, errors, and warnings always show up in the diagnostics log that you can view by calling xdebug_info().
This setting can additionally be configured through the XDEBUG_CONFIG environment variable.
string xdebug.mode = develop #
This setting controls which Xdebug features are enabled.
This setting can only be set in php.ini or files like 99-xdebug.ini that are read when a PHP process starts (directly, or through php-fpm). You can not set this value in .htaccess and .user.ini files, which are read per-request, nor through php_admin_value as used in Apache VHOSTs and PHP-FPM pools.
The following values are accepted:
off Nothing is enabled. Xdebug does no work besides checking whether functionality is enabled. Use this setting if you want close to 0 overhead. develop Enables Development Helpers including the overloaded var_dump(). coverage Enables Code Coverage Analysis to generate code coverage reports, mainly in combination with PHPUnit. debug Enables Step Debugging. This can be used to step through your code while it is running, and analyse values of variables. gcstats Enables Garbage Collection Statistics to collect statistics about PHP’s Garbage Collection Mechanism. profile Enables Profiling, with which you can analyse performance bottlenecks with tools like KCacheGrind. trace Enables the Function Trace feature, which allows you record every function call, including arguments, variable assignment, and return value that is made during a request to a file.
You can enable multiple modes at the same time by comma separating their identifiers as value to xdebug.mode: xdebug.mode=develop,trace .
XDEBUG_MODE environment variable
You can also set Xdebug’s mode by setting the XDEBUG_MODE environment variable on the command-line; this will take precedence over the xdebug.mode setting, but will not change the value of the xdebug.mode setting.
Some web servers have a configuration option to prevent environment variables from being propagated to PHP and Xdebug.
For example, PHP-FPM has a clear_env configuration setting that is on by default, which you will need to turn off if you want to use XDEBUG_MODE .
Make sure that your web server does not clean the environment, or specifically allows the XDEBUG_MODE environment variable to be passed on.
Functions #
xdebug_info( string $category = null ) : mixed #
Show and retrieve diagnostic information
This function presents APIs to retrieve information about Xdebug itself. Which information gets returned, or displayed, depends on which arguments, or none at all, are given.
$category =
The HTML output includes which mode is active, what the settings are, and diagnostic information in case there are problems with debugging connections, opening of files, etc.
Each warning and error in the diagnostics log also links through to the Description of errors documentation page.
$category = ‘mode’ (New in Xdebug 3.1)
The function returns an array of all the enabled modes, whether through xdebug.mode or the XDEBUG_MODE environment variable.
Example:
var_dump ( xdebug_info ( ‘mode’ ) );
?>?phpReturns:
array(3) < [0] =>string(5) "debug" [1] => string(7) "develop" [2] => string(5) "trace" >
$category = 'extension-flags' (New in Xdebug 3.1)
The function returns an array of all the compile flags that were enabled when running ./configure as part of Xdebug's compilation process.
The only flag that is available, is the compression flag. If this flag is enabled, then the xdebug.use_compression setting is available, and enabled by default.
Profiling and Function Trace will create GZip compressed files if the xdebug.use_compression setting is turned on (the default).
Example:
var_dump ( xdebug_info ( 'extension-flags' ) );
?>?phpReturns:
array(1) < [0] =>string(11) "compression" >
This site and all of its contents are Copyright © 2002-2023 by Derick Rethans.
All rights reserved.Установка xDebug под Windows
Привет! Вчера сидели с друзьями в японском ресторане и речь зашла про отладку web-приложений. Я как то пробовал ставить xDebug но что то он не захотел работать. Так вот я им задал вопрос о том зачем нужна отладка в PHP ладно когда пишешь на компилируемом языке программирования (к примеру C++), а в PHP же можно и print_r() использовать для того что бы вывести массив… на что я получил ответ, что с xDebug можно поставить точку останова и посмотреть значения всех переменных и что это гораздо удобней чем просто пользоваться print_r(). Сегодня я проснулся и подумал надо попробовать еще раз установить xDebug использовать удобный инструмент при отладке.
1. Скачаем xDebug для своей версии PHP: http://www.xdebug.org/download.php у меня это (php_xdebug-2.2.1-5.3-vc9.dll для версии PHP 5.3.x)
2. Кладем скачанный файл в папку с расширениями PHP: [путь до php]/php/ext
3. Отредактируем php.ini:
прописываем абсолютный путь до библиотеки (если прописать относительный, библиотека не подключается)
zend_extension='G:\webserver\php\ext\php_xdebug-2.2.1-5.3-vc9.dll'
в конце файла php.ini создаем секцию xdebug со следующими параметрами:
xdebug.remote_enable=on xdebug.remote_handler=dbgp xdebug.remote_host=localhost xdebug.remote_port=9000
Xdebug on Windows
To debug PHP applications with PHP Tools for Visual Studio Code, it is necessary to install and enable Xdebug extension.
With installer
XAMPP or WAMPP will install and configure PHP, Xdebug and Apache server.
Adding Xdebug to existing PHP installation
If you already have PHP installed, but missing Xdebug, download binaries directly from Xdebug
Choose the version depending on your PHP version. You can use the tool provided by Xdebug developers: Xdebug Wizard. Copy and paste your phpinfo() function output or output of php -i command. The tool will give you the correct version to download.
Copy downloaded binaries into the PHP extensions folder( ext sub-folder of the PHP installation).
Configuring Xdebug
You can locate it by running the following command:
php --iniThe command will output similar lines:
Configuration File (php.ini) Path: Loaded Configuration File: C:\Program Files\PHP\v8.1\php.ini Scan for additional .ini files in: (none) Additional .ini files parsed: (none)Open the php.ini file and make sure the following lines are present:
[XDEBUG] zend_extension="C:\Program Files\PHP\v8.1\ext\php_xdebug.dll" xdebug.mode=debug xdebug.client_host = 127.0.0.1 xdebug.client_port = 9003 xdebug.start_with_request=triggerAlter the path to php_xdebug.dll according to your PHP installation and make sure it's an absolute path.
Optionally you can switch xdebug.start_with_request to yes (in Xdebug 2 it was xdebug.remote_autostart = 1 ). This option will instruct Xdebug to contact IDE on each request. By default Xdebug initiates the debug session only when it's instructed to, e.g. when URL has XDEBUG_SESSION_START query parameter, which might complicate scenarios like debugging AJAX requests.
Verify the installation
Verify the installation by running the following command:
php -vThe output should indicate both PHP and Xdebug are installed:
PHP 8.1.0 (cli) (built: Nov 23 2021 21:46:10) (NTS Visual C++ 2019 x64) Copyright (c) The PHP Group Zend Engine v4.1.0, Copyright (c) Zend Technologies with Xdebug v3.1.1, Copyright (c) 2002-2021, by Derick RethansSee Also
- Debug Overview
- Launch Configurations
Настройка Xdebug в PhpStorm на Windows 10

Наконец-то настроил Xdebug. Это такая крутая штука скажу я вам. Показывает всё: что пришло, что ушло, в каком виде и тд. Очень круто и удобно. Но Xdebug надо настроить чтобы все работало.
- Так что, эта статейка будет справочником чтобы не забыть алгоритм настройки.
Исходные данные
- ОП: Windows 10
- IDE: PhpStorm 2022.1
- Local server: Laragon 5.0.0
- PHP: 7.4.33
Важный момент! Версия php должна быть не ниже 7.4.20, иначе xdebug не будет работать. Актуальная версия PHP на момент написания статьи: 7.4.33
Шаг первый. Обновление версии PHP для Laragon

2. Полученный архив вида php-7.4.33-Win32-vc15-x64.zip копируем в папку \bin\php\ вашей установки Laragon. И там распаковываем в папку с тем же именем, например php-7.4.33-Win32-vc15-x64
3. Если Laragon запущен, то останавливаем его, и меняем версию на нужную. И снова запускаем.

Версия PHP обновлена до нужной. Теперь можно заняться xdebug
Шаг второй. Установка Xdebug
- Для Php 7.4.33 нужную версию xdebug просто так не найдешь. Ну почему, у них так на сайте сделано, что только под php 8.0 можно скачать сразу, все остальное только через танцы с бубнами.
- Вариант раз: воспользоваться мастером скачивания
- Вариант два: найти и скачать нужную версию в истории релизов
- Вариант три: сразу скачать нужный файл
2) После скачивания, получим файл вида php_xdebug-3.1.6-7.4-vc15-x86_64.dll . Копируем его в папку с нужной версией PHP по пути \laragon\bin\php\php-7.4.33-Win32-vc15-x64\ext
И переименовываем файл php_xdebug-3.1.6-7.4-vc15-x86_64.dll в php_xdebug.dll для краткости.
3) Запускаем xdebug в Laragon

Заодно можете включить opcache, для более быстрой работы админки на локалке.
4) Теперь надо немного настроить файл php.ini . По дефолту в нем нет настроек раздела xdebug, так что открываем его на редактирование

И в свободном месте добавляем настройки
[XDebug] xdebug.mode=debug xdebug.client_port = 9090Обратите внимание! Использую не штатный порт 9003, а 9090. На штатному порту у меня не завелось, но вы можете и штатный попробовать.

Сохраняем изменения в php.ini и перезагружаем Laragon. На этом установка xbebug завершена.
Шаг третий. Настройка PhpStorm для работы с Xdebug
Осталось настроить PhpStorm.
Расширение Xdebug helper
Первое что нужно сделать — установить расширение для браузера Xdebug helper
Важно! После установки заходим в параметры и устанавливаем IDE key в позицию PhpStorm. Незабываем нажать кнопку Save, после изменения.

Можно и другие расширения использовать. Какие еще есть, смотрим тут.
Основные настройки
Теперь открываем нужный проект в PhpStorm и идем в основные настройки File → Settings → PHP
Ставим тот порт, который указали в настройках php.ini . В нашем случае — 9090 . И снимаем галки с пунктов:
- Force break at first line when no path mapping specified
- Force break at first line when a script is outside the project

В основном разделе PHP укажите вашу версию в CLI Interpreters

к содержанию
Настройка конфигурации дебага
Переходим Run → Edit Configurations

Создаем новую конфигурацию. Выбираем PHP Remote Debug

Теперь настоим ее.

- Nameможет быть любым, но я предпочитаю по названию проекта называть.
- Ставим чек Filter debug connection by IDE key
- Server: указываем хост нашего проекта, в моем случае magazin-skulptur.loc , порт 8080 так по дефолту делает Laragon
- IDE key: указываем PHPSTORM , то есть тот же, что указывали в Xdebug helper
Теперь надо проверить все настройки

Нажимаем Validate. Если все отчекалось, значит настройка прошла успешно

к содержанию
Использование Xdebug
Все настроили, осталось использовать
На нужной странице сайта, включаем Xdebug helper

Включаем прослушивание Run → Start Listening for PHP Debug Connection или если пользуетесь отдельной панелью, то справа сверху трубку нажимаем

Ставим брекпоинты на нужной строке (справа от номера строки) и запускаем дебаг нажатием на жучка. Откроется панель и появиться сообщение что ожидается коннект

После обновления страницы, данные придут в панель. Переходом по стрелке, можно смотреть какие данные приходят и что получается.

Внимание! Включенный Xdebug серьезно нагружает процессор, так что имейте ввиду, что если комп начал тормозить, то имеет смысл отключить Xdebug.
Заключение
Вот и все, обновили версию PHP, установили и настроили Xdebug, теперь ни одна трабла от нас не скроется!
Успехов и берегите себя!
