PHP Debugging Tools xdebug Detailed use tutorial

Source: Internet
Author: User
Tags session id php debug php debugging tools stack trace drupal
Xdebug is a php extension, the official address: https://xdebug.org/index.php, to help developers debug code, this article is mainly to share with you the PHP debugging tool xdebug Detailed use of the tutorial, the latest 2.6 version for the column to explain, hope to help everyone.

It has these features:

Error message instead of PHP:

Add color to your hints to emphasize different information
Large Variable printing:
Enhanced function of print functions such as var_dump (), Print_r (), useful in large-variable printing, avoid crashes
Maximum recursive protection:
Maximum recursive limit can be set to prevent PHP card from dying
Function call Tracking:
Ability to trace function call procedures, display incoming and returned values, memory usage, etc.
Code Coverage Analysis:
You can find out which rows were executed while the code was running.
Garbage Collection Analysis:
Information that shows which variables are cleaned, how much memory is freed, and so on when PHP performs garbage collection
Code Performance Analysis:
Can see the execution time of each part of code, find out the bottleneck of the code running efficiency
Remote debugging:

With the IDE tool for remote breakpoint debugging, let you step-by-step tracking code execution, view or set the values of variables in the run, avoid using var_dump (), Print_r () functions, which is xdebug most commonly used function, very powerful.

Installation:
This is explained in the following environment, other environment please follow the instructions:
Operating system: Windows 10
PHP Version: php-7.1.13-nts (+ bit)
Download: https://xdebug.org/download.php
Please choose the appropriate version according to your environment (PHP version, thread safety, bit width, etc.), here I choose according to the previous environment:
Version: Xdebug 2.6.0,php 7.1 VC14 (the version was released in 2018-01-29)
Php_xdebug-2.6.0-7.1-vc14-nts.dll the downloaded file into the ext directory of PHP
Modify the php.ini file to include the following configuration:
zend_extension= "Php_xdebug-2.6.0-7.1-vc14-nts.dll"
Execute Phpinfo (), if the xdebug extension is already displayed, the installation is successful, if not, check whether the version is selected
The actual use of the installation after the completion of the need for your purpose in the php.ini file in a specific configuration, the following according to the various functions, common instructions

To turn on the XDEBUG mode error message:
As long as the xdebug extension is enabled, the feature is turned on by default and will be displayed incorrectly in the Xdebug style, and if you want to display it in the original PHP style, you can set it in the configuration file: xdebug.default_enable= 0, note that this setting does not mean turning off all features of Xdebug

To configure the display of large variables:
In some programs, variables can be very large, such as the famous Content management system Drupal8 in the node rendering array, if the direct print_r so can memory 8G I5 computer card die, so Xdebug provides configuration of large variable print configuration to avoid this situation, configure the following configuration items:
Xdebug.var_display_max_children
Integer, default 128, maximum number of displayed array child elements or object properties, no limit is set to-1, not affected by remote debugging
Xdebug.var_display_max_data
Integer, default 512, displays the maximum length of the string, 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 properties, Max 1023, can use-1 refers to this maximum number

Maximum recursive protection:
Set the following configuration items:
Xdebug.max_nesting_level
Integer, the default is: 256, no limit is set to-1, infinite recursive protection mechanism, when the recursive call reached the setting when the program is interrupted, note that at this time no error prompts, but directly quit the program

Function call Tracking:
Including the object method call, the function is closed by default, the output call data to a file after opening, view the file can be configured as follows (here the value is set to our most common situation for replication use, more see the configuration instructions below):
Xdebug.auto_trace=1
; Turn on tracking, default is off
Xdebug.trace_output_dir= "C:\root\xdebug\trace"
; Call trace Data Output directory
Xdebug.trace_output_name= "Yunke.%s.%u"
; trace file filename
Xdebug.collect_params=4
; The form of collection function parameters
Xdebug.collect_return=1
; whether to collect function return values
Xdebug.show_mem_delta=1
; Show memory Details
Xdebug.trace_format=0
; The format of the trace file

The above settings will generate an analysis file for all requests, and the call trace analysis can also be triggered by a variable (auto-completion via browser extension, which is also the recommended method, see below), which is to set the variable name Xdebug_trace in the Get/post or cookie. Its value is the key that matches the following settings, configured as follows:
Xdebug.auto_trace=0
; automatic tracking when triggering a variable trigger trace needs to be closed
Xdebug.trace_enable_trigger=1
Xdebug.trace_enable_trigger_value= "Yunke"
This is the value of the above Xdebug_trace variable
If Access URL: Http://www.test.com/index.php?XDEBUG_TRACE=yunke, can trigger the production of trace files
Here "Yunke" is a key value that only matches the configuration file to produce an analysis file, which defaults to null characters

Code Coverage Analysis:
This feature lets us know which lines of code execution are being executed, typically for unit tests, and is configured as follows:
Xdebug.coverage_enable=1
; Code Coverage Analysis Open

The Code coverage analysis is done by invoking the function in the PHP code, and the process is as follows, which results in an array:
Xdebug_start_code_coverage ();//Open overwrite
...//Some code that was analyzed
Var_dump (Xdebug_get_code_coverage ());//Get an array of analysis results

Garbage Collection Analysis:
This feature is turned off by default, and will output garbage collection analysis data to a file, view the file can be configured as follows (this value is set to our most common situation for replication use, more see the configuration instructions below):
Xdebug.gc_stats_enable=1
; Turn on garbage collection analysis
Xdebug.gc_stats_output_dir= "C:\ROOT\XDEBUG\GC"
; Data output directory, default is/tmp
Xdebug.gc_stats_output_name= "Gcstats.%s.%u"
; The output file name, default is: gcstats.%p

Program Performance Analysis:
This feature is turned off by default, when turned on will output profiling data to a file, which is convenient for machine-parsed text format, requires dedicated software to view, configured as follows (this value is set to our most commonly used conditions for replication use, more see the configuration instructions below):
Xdebug.profiler_enable=1
; Turn on performance analysis
Xdebug.profiler_output_dir= "C:\root\xdebug\profiler"
; Profiling file Output Directory
Xdebug.profiler_output_name= "Cachegrind.out.%s.%u"
; Performance analysis output file name

The above settings will generate an analysis file for all requests, and profiling can also take the form of a variable trigger (which can be done automatically via browser extensions, which is also the recommended method, see below), which is to set the variable name xdebug_profile in Get/post or cookie. Its value is the key that matches the following settings, configured as follows:
Xdebug.profiler_enable=0
Automatic analysis needs to be turned off when triggering analysis on variables
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 Access URL: Http://www.test.com/index.php?XDEBUG_PROFILE=yunke
Here "Yunke" is a key value that only matches the configuration file to produce an analysis file, which defaults to null characters

Introduced in the official website many kinds of software to view the output of the analysis files, which wincachegrind in the small program analysis, large programs can not, or even error, by the Cloud customer test using qcachegrind effect is best, It's a kcachegrind version of Windows, and here's a brief introduction to the software:
On the left there is a "Flat profile" panel, with the first column "incl." Is the execution time, including the time of the internal call of the subroutine, the Self column is the time it consumes itself, not the child function calls, the called column is the number of times the function is called;
The time is measured in microseconds of 1 seconds =1000000 microseconds (μs), in a way that can be used in percent

Remote debugging:
Let's take a look at the whole process of remote debugging, first, the browser comes with special parameters to open the script to debug, the script starts to run, at this time Xdebug will be active to the configured debugging client to initiate a connection, and the DBGP protocol and debugging client interaction (debugging the client is often the IDE we use, such as Phpstorm, it needs to listen to debug network port), the debugging client through the protocol let Xdebug step to execute code, display or set the contents of variables in the program, between each step xdebug PHP program suspend execution, this "step" is called a breakpoint, The debug client can set a breakpoint to allow the program to pause at that point, which is called Breakpoint Debugging for the debug client, and the whole process is to execute the code step-by-step in the PHP engine and xdebug the process, and she receives instructions from the debug client.
For remote debugging, the following configuration and restart of PHP are required first:
Xdebug.remote_enable=1
; Remote Debug Switch
Xdebug.remote_host=localhost
Remote debugging Client host address, which is the host address of the IDE, is often localhost
xdebug.remote_port=9000
; Remote Debug port
When configured, we open the script in the browser, we need to send the Get/post variable name xdebug_session_start or cookie variable name xdebug_session, the value is Xdebug and debug the client's communication session ID, is often a special character specified by the IDE, such as phpstorm specified as "Phpstorm", This value can be set in the Xdebug.idekey configuration, the default is an empty string, browser-attached parameters can be automatically completed by the browser extension (see below); The server receives the request and starts the debugging process according to the settings of the Xdebug.remote_mode configuration item if it is "req "Then when the script starts, Xdebug initiates a debug connection to the debug client (IDE), which is also the default value, and if it is" JIT "then only initiates the connection if there is an error, and once the connection to the IDE is successful, the DBGP protocol is used for debugging interaction.
If the server is shared by multiple developers, then the debug client will have multiple, and the Xdebug.remote_host configuration item can only be set to one, at which point the Xdebug.remote_connect_back is set to 1. That will take the IP obtained from the HTTP header as the address of the debug client.
Xdebug when initiating a debug connection, the default timeout is 200 milliseconds, which is set in the Xdebug.remote_timeout configuration item, which is sufficient for native debugging, and if it is a remote network host, you need to increase the value to cope with network latency.


Browser Plugin helper:
As mentioned above, the triggering method to generate analysis, trace files and open remote debugging all need to set specific variables and values in the Get/post or cookie, then we can let the browser do it, this is possible, here is the developer using the most Firefox browser for the column description:
Install the auxiliary plug-in first, open address: https://addons.mozilla.org/en-GB/firefox/addon/xdebug-helper-for-firefox/
You will see Xdebug Helper for Firefox, click on Add to Firefox, follow the instructions
After installation, you need to configure: Press the key combination "Ctrl+shift+a" to open the Add-ons panel, find Xdebug Helper, click Options, enter the IDE remote session ID, analysis key, trace key (corresponding configuration Xdebug.idekey, Xdebug.profiler_enable_trigger_value, Xdebug.trace_enable_trigger_value), click Save, this time the new Web browser address bar will appear a crawler icon, Can choose four states: Debugging, analysis, tracking, disabling, the first three states when the browser opens the connection will be accompanied by additional cookie parameters, such as we choose to analyze, then refresh the connection will be added in the cookie xdebug_profile variable, the value is the key value set earlier, This will allow Xdebug to generate analysis files, function tracking and remote debugging in the same vein.

Phpstorm Debug:
The former said that Xdebug remote debugging is her through the DBGP protocol and debugging client interaction process, the remote debugging client needs to listen to the network port to receive Xdebug initiated debugging connection, here to Phpstorm as a remote debugging client to explain the specific operation.
Phpstorm is a common IDE for developers, Here the 2017.2.4 version, with the well-known content management system Drupal8 to illustrate the debugging process, first you need to install configuration good Xdebug, host selection: localhost, port select default 9000, Firefox installed the previous section mentioned Xdebug Helper For Firefox extensions, and then open the Drupal project that Phpstorm built (don't know how to build a project yet?). Please Baidu or Drupal website), open: File > Default Settings > Languages &frameworks > PHP > Debug > Xdebug
Port set to 9000, other configuration items depending on your situation select, click Apply and OK
Open the Debug Configuration panel (Run > Edit configurations), click on the upper left corner plus select PHP Web application, enter the debug name (optional), enter Drupal here, click on the three-point number of the server line, open the server configuration panel , enter the server name, URL address and port, debugger select Xdebug, path mapping do not tick, click Apply OK, go back to the previous panel, Start URL input "/", the browser chose to install Xdebug Helper for Firefox extension firefox, application OK,
At this point, the Phpstorm interface in the upper right corner of the debug button a row of the drop-down menu automatically selected the newly created debugging "Drupal", click the phone icon (the icon handset into the listening state) or click the menu run | Start listen for PHP Debug connections start listening on port 9000, set a breakpoint in the index file (click the blank on the left side of the line number of the code, a red dot appears), OK, all ready, open Firefox browser, the Address bar crawler icon selected as "Debug", open a Drupal page, Phpstrom will open the lower left corner of the debug panel, which provides a number of buttons for you to manipulate code execution: the variable quantum panel lists all the variables of the current scope, where you can view all the variable contents The watches panel can track the contents of a variable or expression; The Frames panel lists the call stack frames where the current row resides.
How to use Phpstorm for debugging please see the official documentation, which is no longer detailed, and here are some of the Phpstorm help pages available on the website:
Installation configuration:
Https://confluence.jetbrains.com/display/PhpStorm/Zero-configuration+Web+Application+Debugging+with+Xdebug+and+PhpStorm
Debug Operation:
Https://confluence.jetbrains.com/display/PhpStorm/Using+the+PhpStorm+Debugger

Note that when debugging starts, it will stay where the first breakpoint is, and if you do not have a breakpoint set, then the debug session will end immediately, and you can also set the debug to stay on the first line of code (choose Run > Break at Scripts).
If the browser has a 500 error during debugging, and the debug connection is broken, it is likely that the server will terminate the PHP program, if you are fastcgi way to run Apache, the error log resembles "End of script output before headers", Set the Fcgidiotimeout, ipccommtimeout parameter in the server configuration file httpd.conf to the waiting time you want, in seconds, and check the timeout configuration yourself for other environments.


Common configuration:
All settings and details see: https://xdebug.org/docs/all_settings, this article is only about the introduction
Xdebug.trace_output_dir
The Write directory of the function call trace data file, default to/TMP, ensures that the writable
Xdebug.trace_output_name
Trace file filename Guidelines, the default is: Trace.%c For example: yunke.%s.%u will output a path with a footstep name and with a subtle time, as follows: Yunke. C__root_test_index_php.1520473784_260486.xt
Xdebug.auto_trace
Turn on function call tracking, Boolean value, default = 0
Xdebug.collect_assignments
Boolean value, default = 0, whether to add variable assignments in function tracking
Xdebug.collect_includes
Boolean value, default = 1, whether files of include (), include_once (), require (), or require_once () are written to the trace file
Xdebug.collect_params
Integer, default 0, determines function tracking parameter collection, 0 is not collected, 1 parameter type and number, 2 on 1 based on ToolTip information, 3 full variable content (affected by variable output settings), 4 full variable content and variable name, 5php serialized content without variable name
Xdebug.collect_return
Boolean value, default 0, whether to write the return value of a function call to a trace file
Xdebug.show_mem_delta
Integer, default = 0, non-0 value displays memory usage information for function calls
Xdebug.trace_format
Integer, default 0, trace file format, 0 Human readable format (time index, memory usage, etc.) 1 machine readable format 2 human readable format for Web presentation
Xdebug.trace_options
Integer, which defaults to 0, and if set to 1, the trace file is appended instead of overwritten
Xdebug.var_display_max_children
Integer, default 128, displays the maximum number of array child elements or object properties, no limit is set to-1, not affected by remote debugging
Xdebug.var_display_max_data
Integer, default 512, displays the maximum length of the string, 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 properties, Max 1023, can use-1 refers to this maximum number
Xdebug.coverage_enable
Boolean, the default is 1, whether to open the Code coverage analysis, cloud customer measurement of this setting is invalid, open and get analysis results required function
Xdebug.gc_stats_enable
Boolean value, default = 0, whether garbage collection statistics are turned on
Xdebug.gc_stats_output_dir
Write directory for Garbage statistic analysis, note permissions
Xdebug.gc_stats_output_name
The file name of the garbage analysis file, as well as the filename rules for tracking analysis
Xdebug.profiler_enable
Integer, default = 0, 1 o'clock to turn on profiling
Xdebug.profiler_aggregate
Integer, default 0, non 0 o'clock writes multiple requested profiling data to a file for cross-request analysis
Xdebug.profiler_append
Integer, default 0, whether the parse file is in append mode, the file name setting has an effect on the item
Xdebug.profiler_enable_trigger
Integer, default 0, use trigger mode to turn on analysis, turn it off xdebug.profiler_enable
Xdebug.profiler_enable_trigger_value
String. The default is "", the key that triggers the analysis, with Xdebug.profiler_enable_trigger
Xdebug.profiler_output_dir
string, default to/tmp, parse file output directory
Xdebug.profiler_output_name
Parse file name, default is cachegrind.out.%p, see Xdebug.trace_output_name
Xdebug.extended_info
Integer, default 1, whether to force PHP parser to execute extended_info mode
Xdebug.idekey
String, Default: *complex*, debug session ID, send any value by the cloud Guest test browser can start debugging, so she is not a key value, but some debugging clients can use it to determine whether to accept the debug connection, so it is best to unify
Xdebug.remote_addr_header
The default is an empty string "", which specifies which HTTP header represents the debug client address, and the Xdebug.remote_connect_back combination uses the
Xdebug.remote_autostart
Boolean, default 0, which typically starts remote debugging with a specific variable, and if the item is set to 1, it is always turned on
Xdebug.remote_connect_back
Boolean value, default 0, resolves multi-person debugging problems, ignores fixed IP set, indicates 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 remote debugging is enabled
Xdebug.remote_host
String, default: localhost, address of the remote debugging client
Xdebug.remote_log
String, default NULL, remote debug log file name
Xdebug.remote_mode
String, remote debug default, Req script start on link, JIT when error occurs link
Xdebug.remote_port
Remote Debug End host port, default 9000
Xdebug.remote_timeout
Integer, default 200, milliseconds, time to wait for debug links
Xdebug.default_enable
Boolean value, 1 or 0, turns on Xdebug error, default on
Xdebug.max_nesting_level
Integer, which defaults to: 256, an infinite recursive protection mechanism that is interrupted when a recursive call reaches that setting
Xdebug.max_stack_frames
Integer, Default-1, sets how many frames in the stack are displayed when an error is prompted
Xdebug.scream
Boolean value, default = 0, whether "@" is disabled so that errors are forced to be displayed


Functions that are available after the Xdebug extension is open:
When the extension is loaded, the following functions can be used in the PHP script:
(only part of this is listed, see Https://xdebug.org/docs/all_functions)
String Xdebug_call_class ([int $depth = 1])
Show Call class
String Xdebug_call_file ([int $depth = 1])
Show Call File
String Xdebug_call_function ([int $depth = 1])
Returns the Calling function
int xdebug_call_line ([int $depth = 1])
Returns the call line
void Xdebug_disable ()
Disable stack trace
void Xdebug_enable ()
Turn on stack trace
BOOL Xdebug_is_enabled ()
Check if stack trace is turned on
String xdebug_get_collected_errors ([int clean])
Return all error messages from the error set buffer
Array Xdebug_get_headers ()
Returns all header information set by the header () function
NT Xdebug_memory_usage ()
Return memory usage
NT Xdebug_peak_memory_usage ()
Returns the maximum amount of memory used by the script so far
void Xdebug_start_error_collection ()
Collect errors and suppress display
void Xdebug_stop_error_collection ()
Stop error logging and collect from buffer
Float Xdebug_time_index ()
Returns the execution time of the current point, in seconds
Related recommendations:

A brief discussion on PHP7 installation and Debugging Tools Xdebug extension method

About PHP7 How to install the Debug Tools xdebug Extension Tutorial (figure)

Xdebug Configuration Not successful

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.