php 7 xdebug centos 7
Installation
This section describes on how to install Xdebug.
Installing on Linux #
Xdebug’s latest version is 3.0.4.
Linux distributions might be providing an old and/or outdated version. If the package manager installs a version that is no longer supported (see Supported Versions), please install Xdebug with PECL, or from source instead.
Installing with PECL #
You can install Xdebug through PECL on Linux & macOS with Homebrew. Run:
On Apple M1 hardware, you might instead need to use:
You should ignore any prompts to add «extension=xdebug.so» to php.ini — this will cause problems.
If pecl did not add the right line, skip to the Configure PHP section.
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.0.4.
Alternatively you can obtain Xdebug from 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.
You can also browse the source on GitHub at https://github.com/xdebug/xdebug.
Compile #
There is a wizard available that provides you with the correct file to download, and which paths to use.
Debian users can do that with:
And RedHat and Fedora users with:
Unpack the tarball:
You should not unpack the tarball inside the PHP source code tree. Xdebug is compiled separately, all by itself, as stated above.
If phpize is not in your path, please make sure that it is by expanding the PATH environment variable. Make sure you use the phpize that belongs to the PHP version that you want to use Xdebug with. See this FAQ entry if you’re having some issues with finding which phpize to use.
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:
If that file does not exist, but there are other files in a conf.d or similar directory, you can create a new file there too. Please name it 99-xdebug.ini in that case.
There could be more than one php.ini file. In many set-ups there is a different one for the command line (often cli/php.ini ) and the web server (often fpm/php.ini ).
If you want to use Xdebug and OPCache together, you must have the zend_extension line for Xdebug below the line for OPCache, or in a file starting with a higher number (ie. 99-xdebug.ini vs 20-opcache.ini ), otherwise they won’t work properly together.
Add the following line to this PHP ini file:
Restart your webserver, or PHP-FPM, depending on what you are using.
Verify that Xdebug is now loaded.
Create a PHP page that calls xdebug_info(). If you request the page through the browser, it should show you an overview of Xdebug’s settings and log messages.
On Windows, you should place the php_xdebug.dll in the ext/ directory, which is a child directory in your PHP installation tree.
If you have trouble with this, please refer to the installation wizard to help you guide through this process.
With Xdebug loaded, you can now enable individual features, such as Step Debugging, or Profiling.
Related Content #
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.
This video introduces Xdebug 3’s modes — the new way to configure which parts of Xdebug you have enabled.
Related Settings and Functions #
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:
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
All warnings and errors are described on the Description of errors page, with detailed instructions on how to resolve the problem, if possible. All errors are always logged through PHP’s internal logging mechanism (configured with error_log in php.ini ). All warnings and errors also show up in the diagnostics log that you can view by calling xdebug_info().
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 XML element:
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.
Beyond the element, you will find the configuration of features:
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:
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().
Criticals and errors are additionally logged through PHP’s internal logging mechanism (configured with error_log in php.ini ).
This setting can additionally be configured through the XDEBUG_CONFIG environment variable.
string xdebug.mode = develop #
This setting controls which Xdebug features are enabled.
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.
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.
Make sure that your web server does not clean the environment, or specifically allows the XDEBUG_MODE environment variable to be passed on.
Functions #
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 =
Without arguments, this function returns an HTML page which shows diagnostic information. It is analogous to PHP’s phpinfo() function.
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:
Returns:
$category = ‘extension-flags’ (New in Xdebug 3.1)
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:
Returns:
This site and all of its contents are Copyright © 2002-2021 by Derick Rethans.
All rights reserved.
kramarama / xdebug
http://xdebug.org/install.php#configure-php |
http://blog.jetbrains.com/phpstorm/2013/08/debugger-configuration-validation-with-phpstorm/ |
on CentOS: |
1. You need to install PHP’s devel package for PHP commands execution |
yum install php-devel |
yum install php-pear |
2. Next install GCC and GCC C++ compilers to compile Xdebug extension yourself. |
yum install gcc gcc-c++ autoconf automake |
3. Compile Xdebug |
pecl install Xdebug |
4. Find the php.ini file using |
locate php.ini |
And add the following line |
[xdebug] |
zend_extension=»/usr/lib64/php/modules/xdebug.so» |
xdebug.remote_enable = 1 |
5. Restart Apache |
service httpd restart |
6. Test if it works – create test.php with the following code |
This comment has been minimized.
Copy link Quote reply
quamis commented Feb 3, 2015
on step #4, it would be «cleaner» to create xdebug.ini in /etc/php.d/ and put in it
This comment has been minimized.
Copy link Quote reply
socketpair commented Jul 30, 2015
This comment has been minimized.
Copy link Quote reply
hisame64 commented Sep 4, 2015
XDebug supported PHP 5.3 until 2.2.7.
You can install by this command.
This comment has been minimized.
Copy link Quote reply
vasily802 commented Jun 21, 2016
Centos 7:
$ yum install php70u-pecl-xdebug
This comment has been minimized.
Copy link Quote reply
edinhojorge commented Sep 25, 2016
This comment has been minimized.
Copy link Quote reply
technocrusaders commented Oct 9, 2016
This is what i did:
This comment has been minimized.
Copy link Quote reply
radub commented Apr 3, 2018
This comment has been minimized.
Copy link Quote reply
abdelatnova commented Apr 4, 2018
@radub you can take a look at the supported php version for each xdebug version at https://xdebug.org/download.php for your version it’s 2.5.5. You can install that using pecl install Xdebug-2.5.5
This comment has been minimized.
Copy link Quote reply
killrazor commented Apr 4, 2018 •
We have PHP version 5.4.x so I used pecl install xdebug-2.4.1 instead. Found using the link above from @abdelatnova. Everything else went great.
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Русские Блоги
Руководство по настройке локальной и удаленной отладки CentOS7 + Phpstorm + Xdebug Daquan
Неизлечимые заболевания могут быть диагностированы и обработаны через xdebug.remote_log на стороне сервера.
Введение
Новичкам в PHP обычно рекомендуются такие редакторы, как notepad ++. Но после начала использования IDE, таких как phpstrom, есть много преимуществ. Например, при изучении некоторых фреймворков Отладка точки останова Нет замены пониманию всего рабочего механизма и жизненного цикла фреймворка. В производственной среде мониторинг отладочной переменной среды IDE Повышение эффективности разработки Это тоже очень важно. Конечно, в каждой отрасли есть 1% лучших людей, программисты не исключение, и использовать VIM вполне возможно.
2. Подготовка и описание системы
Обратите особое внимание на то, что все содержание этой статьи выполнено в соответствии с 4 этапами предварительной настройки на рисунке ниже. Если вы столкнулись с проблемой, не описанной в этой статье, вы можете нажать «Проверить конфигурацию отладчика на веб-сервере» на первом этапе отладки.Подробные сведения см. В главах 4 и 4 этой статьи.
Три, установка Xdebug
1. Щелкните установить xdebug на шаге 1 на рисунке выше, чтобы ввести инструкции по установке phpstorm для xdebug:
Идея phpstorm для установки xdebug состоит в том, чтобы загрузить скомпилированный двоичный файл с официального сайта xdebug, скопировать его в каталог расширения php, а затем добавить следующую конфигурацию в конец файла php.ini (фактические примеры см. В статьях 3 и 4):
2. Это в основном предназначено для среды разработки PHP на сервере Windows. Здесь мы используем CentOS 7. Поэтому наиболее удобный способ установки:
4. Конфигурация xdebug на стороне сервера. Чтобы
Приведенные выше идеи 1, 2 и 3. заключаются в том, чтобы получить двоичное расширение xdebug.so, а затем поместить соответствующую конфигурацию xdebug в файл php.ini. Конфигурация подробно описана ниже.
По порядку объясните перечисленные выше вопросы:
Обратите внимание, что www.phpcms.com настроен как доменное имя виртуального сайта, тогда соответствующее значение должно быть настроено в / etc / hosts, а именно www.phpcms.com 127.0.0.1
xdebug.remote_mode Режим req означает, что сценарий запускается и подключается. Если это режим jit, он подключается после того, как сценарий генерирует ошибку. Подробнее см. Документацию xdebug по удаленной отладке:https://xdebug.org/docs/remote
В противном случае он застрянет в `debug: ожидании входящего соединения с ключом ide *
Четыре, конфигурация PHPSTORM
Особое внимание, здесь PHPSTORM работает на виртуальной машине, в CentOS 7 это версия для Linux. Если виртуальная машина работает на хосте, измените все следующие 127.0.0.1 на IP-адрес сетевой карты виртуальной машины только для хоста. Затем настройте соответствующее доменное имя и ip в хостах хоста.
1. Настройте исполняемый файл php, используемый PHPSTORM. Настройки-> Langeuages & Frameworks-> PHP, затем Конфигурация проекта, версия php выберите php7, интерпретатор CLI выберите режим ssh, он может быть обнаружен автоматически. Чтобы
4. Проверьте серверную часть и конфигурацию стороны PHPSTORM. Настройки-> Langeuages & Frameworks-> PHP-> Отладка, в предварительной конфигурации, первый шаг, нажмите Проверить, во всплывающем окне введите URL-адресhttp://www.php.com/, Нажмите «Подтвердить». Если информация такая, как показано на рисунке ниже, это означает, что и сервер, и PHPSTORM успешно работают! Если у вас есть другие вопросы в разделе «Информация», задайте их в комментариях к этой статье. Чтобы
Пять, конфигурация подключаемого модуля браузера
что? Он еще не закончен, зачем браузеру подключаемый модуль? Я должен поговорить о коммуникационном процессе отладки Xdebug. Давайте просто будем придерживаться официальных инструкций Xdebug. Общий процесс заключается в том, что PHPSTORM инициирует запрос к браузеру, и браузер возвращается в PHPSTORM по протоколу DBGp. PHPSTORM также возвращает вставленную информацию в браузер через протокол DBGp, и браузер, наконец, возвращает окончательный результат. Результат отправляется в PHPSTORM для отладки и сообщения об ошибках. Подробнее см.https://xdebug.org/docs/remoteиз Communication Set-up With a static IP/single developer Главы. Чтобы
Официальная инструкция:
Шесть, отладка
Настройки-> Языки и рамки-> PHP-> Отладка, в предварительной настройке сначала проверьте настройки. Нет проблем, третий шаг, включить прослушивание отладочного соединения PHP, он также находится в правом верхнем углу интерфейса PHPSTORM.
Чтобы попасть в точку останова на первой строке index.php, щелкните красную точку на рисунке. Затем нажмите на маленького краулера в правом верхнем углу или на Run-debug в меню, PHPSTORM автоматически откроет браузер, как определить, что он был успешным? В это время браузер должен быть пустым и находиться в состоянии загрузки, а в окне отладчика PHPSTORM отслеживаются некоторые глобальные переменные. Поздравляем, вы можете отлаживать PHP, как в среде разработки Microsoft.
Семь, сложное объяснение
1. Официальный документ xdebug считает, что xdebug и zend opcache не универсальны, и после эксперимента автора они не влияют друг на друга. Чтобы
2. Компонент шифрования ionCube необходимо настроить заранее, иначе будет сообщено об ошибке.
Настройка отладки php-кода при помощи Xdebug
Классические методы отладки на PHP — использование функций error_log, print_r и var_dump. Их проблема в том, что они не помогают отслеживать сам процесс работы кода. Однако с этой задачей справляется Xdebug — один из самых популярных инструментов среди PHP-разработчиков, которые хотят работать, а не страдать.
В этой статье будет рассмотрена отладка PHP с помощью связки Xdebug и VSCode. Если вы пользуетесь PHPStorm, то проблем тоже не будет — настройка выполняется даже проще и быстрее.
Возможности Xdebug
Xdebug — это расширение для PHP, которое позволяет использовать удаленный отладчик в IDE через брейк-пойнты. С его помощью вы можете отслеживать значения переменных. Как итог — ошибки в коде обнаруживаются быстрее, чем при использовании error_log, print_r и var_dump.
Еще одна полезная функция — трассировка стека. Она выводит подробный путь, который привел приложение к ошибке. Он содержит параметры, переданные в функцию. Xdebug также можно использовать как профайлер для поиска узких мест кода. Если добавить внешние инструменты, то получится визуализировать графики производительности. Например, можно использовать WebGrind — набор PHP-скриптов для удобного вывода статистики прямо в браузере.
Кроме того, с помощью Xdebug вы можете проследить, какая часть кода выполняется в процессе запроса. Это дает информацию о том, как хорошо код покрыт тестами.
Подключение Xdebug
Для работы Xdebug PHP должен быть в режиме CGI. Посмотрим на примере хостинга Timeweb, как его включить.
Подключаемся к серверу через SSH. Можно использовать консоль в панели управления Timeweb.
Переходим в папку cd-bin сайта:
Создаем символическую ссылку командой:
Остаемся в директории cgi-bin и копируем файл php.ini:
Теперь мы можем управлять параметрами PHP директивами в файле php.ini. Он находится в папке cgi-bin. Открываем его и вставляем в конце следующие строки:
Если указанный порт занят, укажите другой. Можно использовать стандартный для Xdebug — 9000. В качестве idekey я указал VSCODE. Если будете настраивать конфигурацию для PHPStorm, впишите его.
Чтобы проверить, работает ли Xdebug, создадим в корне сайта файл Myfile.php со следующим содержимым:
Открываем файл в браузере и проверяем, что все параметры указаны верно.
Организация удаленного подключения
Чтобы выполнять PHP Debug на локальной машине, нужно настроить связь IDE и сервера через SSH-туннель.
На Linux все выполняется парой команд.
Приватный ключ сохраняется на локальной машине, а публичный добавляется на сервер. Подробнее об этом, а также о настройке SSH на Windows, вы можете узнать из этой статьи.
На Linux туннель создается командой:
На Windows туннель настраивается через утилиту PuTTY.
Сессия сохранится под тем именем, которое мы указали в разделе Session. В дальнейшем нужно будет просто запускать ее заново.
Настройка VSCode
Чтобы работать с Xdebug в VSCode, установим два расширения: Sync-Rsync и PHP Debug. Первое нужно для работы с удаленным сервером, второе — для отладки скриптов.
После установки расширений создаем на локальной машине пустую папку и открываем ее через VSCode: «Файл» — «Открыть папку».
Путь /home/user/.ssh/id_rsa — это место, где лежит файл с закрытой частью SSH-ключа.
После сохранения файла settings.json нажимаем в VSCode F1, выполняем команду Sync Remote to Local. В локальную папку, указанную в настройках, скопируются все файлы с сервера.
На этом настройка IDE завершена. Можно приступать к тестированию кода.
Debug кода
Мы настроили среду, теперь разберемся, как пользоваться Xdebug.
Переходим в режим «Отладка» и проверяем, что выделен пункт Listen for XDebug. Нажимаем на зеленый треугольник или на клавишу F5.
После перезагрузки сайта в браузере возвращаемся в VSCode. В отладчике должны отобразиться глобальные переменные и их значения на момент обработки кода в брейк-пойнте. Вы можете перемещаться по коду, отслеживая изменение переменных на каждом шаге.
Профилирование с визуализацией результатов
Чтобы использовать Xdebug profiler на полную мощность, установим WebGrind. Это набор скриптов, который выводит статистику в браузере. С его помощью можно посмотреть список вызванных функций, количество вызовов, общее затраченное время на вызов и выполнение.
Затем нужно открыть файл config.php, который находится в распакованной папке webgrind-master. В нем отредактируем две строки:
После такой настройки можно выполнять на Xdebug профилирование. Открываем наш тестовый скрипт в браузере. Затем переходим по ссылке www.domain/webgrind-master. В выпадающем списке выбираем только что запущенный скрипт и нажимаем на кнопку Update.
Функции можно скрывать или раскрывать, чтобы посмотреть развернутую статистику. Инструмент также умеет отображать графы вызова функций — для этого используется режим Show Call Graph.
Вывод: когда использовать Xdebug?
Xdebug существенно упрощает отладку PHP-кода. Конечно, если ваш текущий инструментарий удовлетворяет все потребности в поиске багов, то устанавливать дополнительное расширение смысла нет. Но, как показывает практика, без Xdebug сложно провести правильное модульное тестирование или отладку через удаленные брейк-пойнты с возможностью пошаговой проверки кода.