Home > Backend Development > PHP Tutorial > Detailed usage tutorial of php debugging tool Xdebug

Detailed usage tutorial of php debugging tool Xdebug

小云云
Release: 2023-03-21 15:06:02
Original
11234 people have browsed it

xdebug is a php extension, the official address: https://xdebug.org/index.php, used to help developers debug code. This article mainly shares with you the detailed usage tutorial of the php debugging tool Xdebug. The latest version 2.6 is Let’s explain it in a row, I hope it can help everyone.

It has these functions:

Replace the php error prompt:

Add color matching to the prompt to emphasize different information
Large variable printing:
Enhance var_dump (), print_r() and other printing functions are very useful when printing large variables to avoid crashes
Maximum recursion protection:
You can set a limit on the maximum number of recursions to prevent PHP from getting stuck
Function call tracking :
Can track the function call process, display the incoming and returned values, memory usage, etc.
Code coverage analysis:
Can find out which lines were executed when the code was running
Garbage collection analysis:
When PHP performs garbage collection, display information such as which variables are cleaned, how much memory is released, etc.
Code performance analysis:
You can see the execution time of each part of the code and find out the bottleneck of the code running efficiency
Remote debugging:

Cooperate with IDE tools for remote breakpoint debugging, allowing you to track the execution of the code step by step, view or set the values ​​of various variables during operation, and avoid using var_dump(), print_r(), etc. Function, which is also the most commonly used function of xdebug, is very powerful.

Installation:
The following environment is used to illustrate. For other environments, please follow the prompts:
Operating system: Windows 10
php version: php-7.1.13-nts(32 bit)
Download: https://xdebug.org/download.php
Please choose the appropriate version according to your own environment (php version, whether it is thread-safe, bit width, etc.). Here the author chooses based on the previous environment:
Version: Xdebug 2.6.0, PHP 7.1 VC14 (32 bit) This version was released on 2018-01-29
Put the downloaded file php_xdebug-2.6.0-7.1-vc14-nts.dll into the ext directory of php
Modify the php.ini file and add the following configuration:
zend_extension="php_xdebug-2.6.0-7.1-vc14-nts.dll"
Execute phpinfo(). If the xdebug extension is displayed, the installation is successful. , if not, please check whether you have selected the correct version
After the installation is completed, you need to make specific configurations in the php.ini file according to your purpose for actual use. The following is a common description based on each function

Enable error prompts in Xdebug mode:
As long as the xdebug extension is enabled, this function is enabled by default, and errors will be displayed in the xdebug style. If you want to display in the original php style, you can set it in the configuration file: xdebug .default_enable=0, note that this setting item does not refer to turning off all functions of xdebug

Configure the display of large variables:
In some programs, the variables will be very large, such as the nodes in the famous content management system drupal8 Rendering array, if you directly print_r, it will freeze the I5 computer with 8G memory, so Xdebug provides a large variable printing configuration to avoid this situation. Configure the following configuration items:
xdebug.var_display_max_children
Integer, default 128 , the maximum number of displayed array sub-elements or object attributes. If there is no limit, set it to -1. It will not be affected during remote debugging.
xdebug.var_display_max_data
Integer, default 512, the maximum length of the displayed string, no The limit is set to -1, which does not affect remote debugging
xdebug.var_display_max_depth
Integer, default 3, the maximum nesting depth when displaying array or object attributes, the maximum is 1023, you can use -1 to refer to this maximum number

Maximum recursion protection:
Set the following configuration items:
xdebug.max_nesting_level
Integer, the default is: 256, unlimited setting to -1, unlimited recursion protection mechanism, when the recursive call reaches The program is interrupted when setting this. Note that no error message will appear at this time, but the program will be exited directly

Function call tracking:
Including object method calls, this function is turned off by default. After it is turned on Output the call data to a file and view the file. The configuration is as follows (the value here is set to our most commonly used situation for copying and use. See the configuration instructions below for more):
xdebug.auto_trace=1
;Enable tracing, the default is off
xdebug.trace_output_dir="C:\root\xdebug\trace"
;Call the tracing data output directory
xdebug.trace_output_name="yunke.%s.%u"
;The file name of the tracking file
xdebug.collect_params=4
;The form of the collection function parameters
xdebug.collect_return=1
;Whether to collect the function return value
xdebug.show_mem_delta= 1
;Show memory details
xdebug.trace_format=0
;The format of the trace file

The above settings will generate analysis files for all requests, and the call trace analysis can also be triggered by variables. (This can be done automatically through browser extensions, which is also the recommended method, see below), that is, setting the variable name XDEBUG_TRACE in GET/POST or cookies. Its value is the key that matches the following settings. The configuration is as follows:
xdebug.auto_trace=0
;Auto tracing needs to be turned off when variable trigger tracing is enabled
xdebug.trace_enable_trigger=1
xdebug.trace_enable_trigger_value="yunke"
;This is the value of the above XDEBUG_TRACE variable
If you visit the URL: http://www.test.com/index.php?XDEBUG_TRACE=yunke, you can trigger the generation of the tracking file
Here "yunke" is a key value, which can only be generated if it matches the configuration file Analysis file, the default is empty character

Code coverage analysis:
This function allows us to know which lines have been executed during code execution. It is usually used for unit testing. The configuration is as follows:
xdebug.coverage_enable =1
;Code coverage analysis is turned on

Code coverage analysis is performed by calling functions in the PHP code. The process is as follows, and an array result will be obtained:
xdebug_start_code_coverage();// Turn on overwriting
...//Some code being analyzed
var_dump(xdebug_get_code_coverage());//Get an array of analysis results

Garbage collection analysis:
This function is turned off by default , after being turned on, the garbage collection analysis data will be output to a file, just view the file, the configuration is as follows (the value here is set to our most commonly used situation for copying and use, see the configuration instructions below for more):
xdebug.gc_stats_enable =1
;Enable garbage collection analysis
xdebug.gc_stats_output_dir="C:\root\xdebug\gc"
;The data output directory, the default is /tmp
xdebug.gc_stats_output_name="gcstats.% s.%u”
;Output file name, the default is: gcstats.%p

Program performance analysis:
This function is turned off by default. When turned on, the performance analysis data will be output to a file. The file is in a text format that is easy for machine parsing and requires special software to view. The configuration is as follows (the value is set here For our most commonly used situations for replication and use, see the configuration instructions below for more):
xdebug.profiler_enable=1
; Turn on performance analysis
xdebug.profiler_output_dir="C:\root\xdebug\profiler "
;Performance analysis file output directory
xdebug.profiler_output_name="cachegrind.out.%s.%u"
;Performance analysis output file name

The above settings will be generated for all requests Analyzing files and performance analysis can also use variable triggering (can be done automatically through browser extensions, which is also a recommended method, see below), that is, setting the variable name XDEBUG_PROFILE in GET/POST or cookie, its value is as follows The key that the setting item matches is configured as follows:
xdebug.profiler_enable=0
; Automatic analysis needs to be turned off when variable trigger analysis is enabled
xdebug.profiler_enable_trigger=1
xdebug.profiler_enable_trigger_value="yunke"
;This is the value of the above XDEBUG_PROFILE variable
can trigger the generation of analysis files, such as visiting the URL: http://www.test.com/index.php?XDEBUG_PROFILE=yunke
Here "yunke" is A key value. An analysis file can only be generated if it matches the configuration file. The default is an empty character

. On the official website, many softwares are introduced to view the output analysis files. Among them, WinCacheGrind is acceptable in small program analysis, and large-scale program analysis is acceptable. The program will not be able to cope with it, and even errors will occur. After Yunke's test, QCacheGrind has the best effect. It is the Windows version of KCacheGrind. Here is a brief introduction to the software:
After opening, there is a "Flat Profile" panel on the left. The first column "Incl." is the execution time, including the time of internally called subroutines; the Self column is the time consumed by itself, excluding subfunction calls; the Called column is the number of times the function has been called; Function is the function name; The Location column is the file location;
The time is in microseconds. 1 second = 1000000 microseconds (μs), which can be expressed as a percentage.

Remote debugging:
Let’s take a look at remote debugging first The whole process of It is often the IDE we use, such as phpstorm, which needs to monitor the debugging network port). The debugging client uses the protocol to let Xdebug execute the code step by step, display or set the variable content in the program, and Xdebug will hang the php program between each step. To pause execution, this "step" is also called a breakpoint. The debugging client can set a breakpoint to pause the program there. For the debugging client, this is also called breakpoint debugging. The whole process is Xdebug in PHP. The engine executes the code step by step and operates the process. She receives instructions from the debugging client.
To perform remote debugging, the specific operations are as follows, first you need the following configuration and restart php:
xdebug.remote_enable=1
;Remote debugging switch
xdebug.remote_host=localhost
;Remote debugging client The host address, that is, the address of the host where the IDE is located, is often localhost
xdebug.remote_port=9000
; the remote debugging port
After configuring, we open the script in the browser and need to send GET/ when opening it POST variable name is , the default is an empty string; the parameters attached to the browser can be automatically completed through the browser extension (see below); after receiving the request, the server starts the debugging process according to the setting of the xdebug.remote_mode configuration item. If the configuration item is "req" Then when the script first starts, Xdebug will initiate a debugging connection to the debugging client (IDE). This is also the default value. If it is "jit", it will only initiate the connection when an error occurs. Once the connection with the IDE is successfully established, DBGp will be used. protocol for debugging interactions.
If the server is shared by multiple developers, there will be multiple debugging clients, and the xdebug.remote_host configuration item can only be set to one. At this time, you can set xdebug.remote_connect_back to 1, which will use the The IP obtained in the http header is used as the address of the debugging client.
The default timeout time of Xdebug when initiating a debugging connection is 200 milliseconds. This value is set in the xdebug.remote_timeout configuration item. This value is sufficient for local debugging. If it is a remote network host, the value needs to be increased to cope with it. Network latency.


Browser plug-in assistance:
As mentioned above, triggering analysis, tracking files and enabling remote debugging all require setting specific variables and values ​​in GET/POST or cookies, then we Can you let the browser do it for you? This is possible. Here is the list of Firefox browsers used most by developers:
Install the auxiliary plug-in first and open the address: https://addons.mozilla.org/en -GB/firefox/addon/xdebug-helper-for-firefox/
You will see Xdebug Helper for Firefox, click Add to Firefox and follow the prompts
After the installation is complete, you need to configure: Press the key combination "ctrl+shift+a" to open the add-on panel, find Xdebug Helper, click Options, and enter the IDE remote session id, analysis key, and tracking key respectively (corresponding to xdebug.idekey in the configuration) , xdebug.profiler_enable_trigger_value, xdebug.trace_enable_trigger_value), click Save. At this time, a crawler icon will appear in the browser address bar of the newly opened web page. Four states can be selected: debugging, analysis, tracking, and disabled. Browse in the first three states. When the server opens the connection, it will be accompanied by additional cookie parameters. For example, if we choose analysis, then the XDEBUG_PROFILE variable will be added to the cookie when the connection is refreshed. The value is the key value set previously. This will allow Xdebug to generate analysis files, function tracing and remote The same goes for debugging.

phpstorm debugging:
As mentioned above, Xdebug's remote debugging is the process in which she interacts with the debugging client through the DBGp protocol. The remote debugging client needs to listen to the network port to receive the debugging connection initiated by Xdebug. Here is PhpStorm serves as a remote debugging client to explain the specific operations.
PhpStorm is a commonly used IDE for developers. The 2017.2.4 version is used here. The famous content management system drupal8 is used to illustrate the debugging process. First, you need to install and configure Xdebug. Host selection: localhost, port selection default 9000, Firefox browser Install the Xdebug Helper for Firefox extension mentioned in the previous section, then open the drupal project created by PhpStorm (still don’t know how to create the project? Please visit Baidu or drupal official website), open: file > Default Settings > Languages ​​&Frameworks > PHP > Debug > Application, enter the debugging name (optional), enter drupal here, click the three dots in the Server line, open the server configuration panel, enter the server name, url address and port, select Xdebug as the debugger, do not check the path mapping, click Apply OK , return to the previous panel, enter "/" in the Start URL, select Firefox with the Xdebug Helper for Firefox extension installed in the browser, and apply OK.
At this time, the drop-down menu in the row of debugging buttons in the upper right corner of the phpstorm interface automatically selects the just-created Debugging "drupal", click the phone icon (the icon receiver changes to the listening state) or click the menu Run | Start listen for PHP Debug Connections to start listening to the 9000 port, and set a breakpoint in the index file (click on the left side of the code line number Blank, red dot appears), everything is ready, open the Firefox browser, select the address bar crawler icon as "debug", open a drupal page, at this time phpstrom will open the debugging panel in the lower left corner, which provides There are many buttons for you to operate code execution: the variable subpanel lists all variables in the current scope, where you can view the contents of all variables; the Watches panel can track the contents of variables or expressions; the Frames panel lists the current line The call stack frame in which it is located.
Please check the official documentation for how to use phpstorm for debugging. I will not go into details. Here are some debugging help document pages provided by the phpstorm official website:
Installation configuration:
https://confluence.jetbrains.com/display /PhpStorm/Zero-configuration+Web+Application+Debugging+with+Xdebug+and+PhpStorm
Debugging operation:
https://confluence.jetbrains.com/display/PhpStorm/Using+the+PhpStorm+Debugger

Note that after debugging starts, it will stay at the location of the first breakpoint. If you do not set a breakpoint, the debugging session will end immediately. You can also set debugging to stay at the first line of code ( Select Run > Break at first line in PHP scripts).
If a 500 error occurs in the browser during debugging and the debugging connection is disconnected, it is likely that the server has terminated the php program. If you are running Apache in FastCGI mode, the error log will be similar to "End of script output before headers" , please set the FcgidIOTimeout and IPCCommTimeout parameters in the server configuration file httpd.conf to the waiting time you want in seconds. In other environments, please check the timeout configuration by yourself.


Common configuration:
For all settings and details, please see: https://xdebug.org/docs/all_settings. This article only gives a general introduction
xdebug.trace_output_dir
Function call tracking The writing directory of the data file, the default is /tmp, ensure that it can be written
xdebug.trace_output_name
File name guide for the trace file, the default is: trace.%c For example: yunke.%s.%u will output the band The script name of the path and the subtle time are as follows: yunke.C__root_test_index_php.1520473784_260486.xt
xdebug.auto_trace
Enable function call tracing, Boolean value, the default is 0
xdebug.collect_assignments
Boolean value , the default is 0, whether to add variable assignments in function tracing
xdebug.collect_includes
Boolean value, the default is 1, whether to write include(), include_once(), require() or require_once() files Trace file
xdebug.collect_params
Integer, default 0, determines the collection of parameters for function tracing, 0 means no collection, 1 the type and number of parameters, 2 adds tool tip information based on 1, 3 full variable content (affected by variable output settings), 4 full variables Content and variable names, 5php serialized content has no variable name
xdebug.collect_return
Boolean value, default 0, whether to write the return value of the function call to the tracking file
xdebug.show_mem_delta
Integer, default Is 0, non-zero values ​​will display the memory usage information of function calls
xdebug.trace_format
Integer, default 0, the format of the trace file, 0 is the human-readable format (time index, memory usage, etc.) 1 Machine-readable format 2 Human-readable format is displayed on the web page
xdebug.trace_options
Integer, default is 0, if set to 1, then the trace file is appended instead of overwriting
xdebug.var_display_max_children
Integer, default 128, the maximum number of array sub-elements or object attributes displayed, no limit set to -1, not affected during remote debugging
xdebug.var_display_max_data
Integer, default 512, display string Maximum length, not limited to -1, does not affect remote debugging
xdebug.var_display_max_depth
Integer, default 3, maximum nesting depth when displaying array or object attributes, maximum 1023, you can use -1 to refer to this Maximum number
xdebug.coverage_enable
Boolean, the default is 1, whether to enable code coverage analysis, Yunke actually measured that this setting item is invalid, you need to use the function
xdebug.gc_stats_enable
Boolean value to enable and obtain the analysis results , the default is 0, whether to enable garbage collection statistical analysis
xdebug.gc_stats_output_dir
The writing directory for garbage statistical analysis, pay attention to the permissions
xdebug.gc_stats_output_name
The file name of the garbage analysis file, and the tracking analysis The file name rules are the same
xdebug.profiler_enable
Integer, the default is 0, when it is 1, the performance analysis function will be enabled
xdebug.profiler_aggregate
Integer, the default is 0, when it is not 0, the analysis of multiple requests will be enabled Write data to a file for cross-request analysis
xdebug.profiler_append
Integer, default 0, whether the analysis file uses append mode, the setting of the file name has an impact on this item
xdebug.profiler_enable_trigger
Integer, default is 0, use trigger mode to turn on the analysis function. When turning it on, you need to turn off xdebug.profiler_enable
xdebug.profiler_enable_trigger_value
string. The default is "", the key to trigger analysis, use
xdebug.profiler_output_dir
string with xdebug.profiler_enable_trigger, the default is /tmp, the analysis file output directory
xdebug.profiler_output_name
The name of the analysis file, The default is cachegrind.out.%p, see xdebug.trace_output_name
xdebug.extended_info
Integer, the default is 1, whether to force the PHP parser to execute extended_info mode
xdebug.idekey
String, default : *complex*, debugging session id, any value sent by the Yunke test browser can start debugging, so it is not a key value, but some debugging clients can use it to determine whether to accept the debugging connection, so it is best to unify
xdebug.remote_addr_header
The default is an empty string "", used to specify which http header represents the debugging client address, used in combination with xdebug.remote_connect_back
xdebug.remote_autostart
Boolean value, default 0, usually Use a specific variable to start remote debugging. If this item is set to 1, then it is always enabled
xdebug.remote_connect_back
Boolean value, default 0, solves the problem of multi-person debugging, ignores the set fixed IP, instructs the server based on Request address link
xdebug.remote_cookie_expire_time
integer. Default 3600, remote debugging cookie expiration time
xdebug.remote_enable
Boolean value, default 0, whether to enable remote debugging
xdebug.remote_host
String, default: localhost, the address of the remote debugging client
xdebug.remote_log
String, default empty, remote debugging log file name
xdebug.remote_mode
String, remote debugging default, req script will be linked as soon as it is started, jit will be linked when an error occurs
xdebug.remote_port
Remote debugging host port, default 9000
xdebug.remote_timeout
Integer, default 200, unit millisecond, time to wait for debugging link
xdebug.default_enable
Boolean value, 1 or 0, enable error prompts in xdebug mode, enabled by default
xdebug.max_nesting_level
Integer, default is: 256, infinite recursion protection mechanism, when the recursive call reaches this setting, the program will be interrupted
xdebug .max_stack_frames
Integer, default value -1, set how many frames in the stack are displayed when error prompts
xdebug.scream
Boolean value, default is 0, whether to disable "@" so that errors can be Forced display


Functions available after the xdebug extension is turned on:
When the extension is loaded, the following functions can be used in the php script:
(Only some are listed here, see https for all ://xdebug.org/docs/all_functions)
string xdebug_call_class([int $depth = 1])
Display call class
string xdebug_call_file([int $depth = 1])
Display call File
string xdebug_call_function([int $depth = 1])
Returns the calling function
int xdebug_call_line([int $depth = 1])
Returns the calling line
void xdebug_disable()
Disable stack tracing
void xdebug_enable()
Enable stack tracing
bool xdebug_is_enabled()
Check whether stack tracing is enabled
string xdebug_get_collected_errors([int clean])
Return all error messages from the error set buffer
array xdebug_get_headers()
Return header() All header information set by the function
nt xdebug_memory_usage()
Returns the memory usage
nt xdebug_peak_memory_usage()
Returns the maximum memory usage used by the script so far
void xdebug_start_error_collection()
Collect errors and suppress display
void xdebug_stop_error_collection()
Stop error recording and collect from the buffer
float xdebug_time_index()
Return the execution time of the current point, in seconds
Related recommendations:

A brief description of how to install the debugging tool Xdebug extension for PHP7

Tutorial on how to install the debugging tool Xdebug extension for PHP7 (picture)

Xdebug configuration failed

The above is the detailed content of Detailed usage tutorial of php debugging tool Xdebug. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template