This section provides the list of solutions and workarounds for common problems with Debugging in PhpStorm.
Collecting PhpStorm debugging logs
If your issue is not addressed in this section, contact our support engineers. If asked to provide deployment logs, follow the instructions to collect them.
Collect debugging logs
-
Select in the main menu.
-
In the Custom Debug Log Configuration dialog that opens, add the following lines depending on the issues you are experiencing:
-
Issues with PHP debugging:
#com.jetbrains.php.debug
-
-
Click OK and reproduce the issue.
-
Locate the log file by selecting (for Windows and Linux) or (for macOS).
If necessary, you can locate the log manually:
- Syntax
-
%HOMEPATH%.<product><version>systemlog
- Example
-
C:UsersJohnS.PhpStorm2022.3systemlog
- Syntax
-
~/Library/Logs/<product><version>
- Example
-
~/Library/Logs/PhpStorm2022.3
- Syntax
-
~/.<product><version>/system/log
- Example
-
~/.PhpStorm2022.3/system/log
The most recent log file is named idea.log; older files names end with a number, that is idea.log.1, idea.log.2, and so on. In most cases you need only the most recent one.
-
Attach the log file(s) to the issue or forum thread.
Collecting Xdebug logs
When using Xdebug, it is possible to make it log its actions.
-
In the Settings 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: <path to php.ini> file. Close all the dialogs and switch to the tab where the php.ini file is opened.
-
In the php.ini, enable Xdebug logging by adding the following line:
xdebug.log=»path_to_log/xdebug.log»
xdebug.remote_log=»path_to_log/xdebug.log»
The log file contains the raw communication between PhpStorm and Xdebug as well as any warnings or errors:
Log opened at 2018-01-08 08:14:28 I: Connecting to configured address/port: 127.0.0.1:9000. I:
Connected to client. -> <init xmlns=»urn:debugger_protocol_v1″
xmlns:xdebug=»https://xdebug.org/dbgp/xdebug»
fileuri=»file:///C:/Projects/Samples/DebuggingTutorial/debugging.php» language=»PHP»
protocol_version=»1.0″ appid=»3040″ idekey=»11774″><engine version=»2.2.5″><![CDATA[Xdebug]]></engine><author><![CDATA[Derick
Rethans]]></author><url><![CDATA[https://xdebug.org]]></url><copyright><![CDATA[Copyright
(c) 2002-2018 by Derick Rethans]]></copyright></init><- step_into -i 5 -> <response xmlns=»urn:debugger_protocol_v1″
xmlns:xdebug=»https://xdebug.org/dbgp/xdebug» command=»step_into» transaction_id=»5″ status=»break»
reason=»ok»>< xdebug:message
filename=»file:///C:/Projects/Samples/DebuggingTutorial/debugging.php» lineno=»2″></xdebug:message></response>
Making sure Xdebug or Zend Debugger are installed and configured
To debug PHP code with PhpStorm, make sure that you have a debugging engine, either Xdebug or Zend Debugger, installed and configured properly.
These tools cannot be used simultaneously because they block each other. To avoid this problem, you need to update the corresponding sections in the php.ini file as described in Configure Xdebug and Configure Zend Debugger.
To validate the debugging engine configuration, perform the steps described in Validate the Configuration of a Debugging Engine
Startup warnings and errors preventing the debugger from working
When running PHP, it can happen that a startup warning or error is displayed. When this is the case, the debugger may fail to work. PhpStorm will also not be able to recognize the debugger being used.
To verify that no startup warnings or errors are displayed, run the following command:
php —version
This will return a message similar to the following:
<some error/warning> PHP 7.1.20 (cli) (built: Jul 20 2018 10:27:12) ( NTS ) Copyright (c) 1997-2018
The PHP Group Zend Engine v3.1.0, Copyright (c) 1998-2018 Zend Technologies with Zend OPcache v7.1.20,
Copyright (c) 1999-2018, by Zend Technologies with Xdebug v2.6.0, Copyright (c) 2002-2018, by Derick Rethans
If any errors or warnings are present on the first lines, it’s recommended to fix them before continuing.
Debugger cannot connect
When the debugger cannot connect or refuses the connection, check the following:
-
Make sure Xdebug or Zend Debugger are configured to connect to the host and port PhpStorm is running on.
-
In the Xdebug configuration, make sure
xdebug.remote_host
andxdebug.remote_port
(xdebug.client_host
andxdebug.client_port
for Xdebug 3) are correct. Refer to the Xdebug documentation for details. -
When using Zend Debugger, make sure the generated PhpStorm bookmarklets or a Browser Debugging Extension is configured to use the correct IP address and port.
-
When using a remote PHP interpreter, verify the steps outlined in Remote debugging via SSH tunnel.
-
-
In the Settings dialog (Ctrl+Alt+S), navigate to and make sure PhpStorm and Xdebug / Zend Debugger are configured with the same port numbers.
-
In PhpStorm, enable listening to incoming debug connections by either clicking on the toolbar/the status bar or selecting in the main menu. This will ensure PhpStorm reacts when a debugging session is started and opens the Debug tool window automatically. Before launching the script, make sure that either a breakpoint is set or the Break at first line in PHP scripts option is enabled on the Debug page of the Settings dialog Ctrl+Alt+S.
-
Verify no firewall, router or ISP is blocking the connection. This can be verified by running
telnet host 9000 (for Xdebug)
ortelnet host 10137
(for Zend Debugger) from remote server (where host is an IP address of your local machine running PhpStorm) and checking a connection is established. You can use http://www.canyouseeme.org or a similar service to check for opened inbound ports. -
Make sure that
xdebug.remote_host
(for Xdebug 2),xdebug.client_host
(for Xdebug 3), orzend_debugger .allow_hosts
(for Zend Debugger) are properly configured. The value can be a host name (for example, localhost) or an IP address of the machine where PhpStorm is running, and it must be pingable from the server. When using Xdebug, xdebug.remote_connect_back (for Xdebug 2) or xdebug.discover_client_host (for Xdebug 3) can be used for troubleshooting.
No Debug Server is Configured
If you initiate a Zero-configuration debugging session without having configured a Debug server, upon establishing connection PhpStorm displays the Incoming Connection dialog where suggests importing mappings from a server access configuration (deployment configuration). If you choose Import mappings from deployment, PhpStorm tries to detect the most suitable deployment configuration, preselects it in the Deployment list, and the Preview area shows the absolute path to the project file, which corresponds to the currently executed script according to the mappings from the selected configuration.
If PhpStorm does not detect a relevant configuration:
-
Choose the most suitable configuration from the list or click and create a new configuration in the Deployment dialog that opens, whereupon the new configuration is added to the list.
-
In the Deployment root field, type the absolute path to the server root folder.
You can also select the Manually choose local file or project option, in this case PhpStorm displays the project tree view where you can select a project file and map the currently executed script to it. You can also select and map the entire project.
To continue debugging with the imported or manually specified configuration settings, click Accept.
Remote file path is not mapped to any file path in project
In some cases, the debugger can connect, but you get the error messages indicating that no mapping between the remote and project files is defined. This means that PhpStorm cannot determine which local file corresponds to the file being debugged.
To solve this problem, click Click to set up path mappings and providing the necessary path mappings.
Path mappings are used when the paths to the files processed by the server differ from the paths to the files in the PhpStorm project. This happens in the following cases:
-
The server is remote and the project files are local copies of the originals.
-
The files processed by the server and the files opened in the IDE are the same, but symlinks are used. Because the debugger resolves symlinks during a debugging session, you need to tell the IDE actual solute physical paths to the files on the server.
To configure path mappings, in the Settings dialog (Ctrl+Alt+S), navigate to .
If the files that the server processes are in the project and you are not using symlinks, clear the Use path mappings checkbox. In this case, the IDE will open files according to the paths received from the debugger.
A path mapping specified for a parent directory is automatically applied to all its subdirectories. If necessary, path mappings for any subdirectory or file can be specified.
See Configure synchronization with a server for more details.
Breakpoints are not being hit
When breakpoints are not being hit but the debugger seems to connect, verify the following:
-
Verify the breakpoint is not disabled. Using the menu command Ctrl+Shift+F8, check that breakpoints are enabled. Select the checkbox next to a breakpoint to enable it.
-
Make sure that path mappings are correct.
-
On macOS, when a file or folder is renamed using Finder, and the letter case is changed, PhpStorm may not be able to find the files. If renaming is required, make sure to do it in the IDE or using a terminal and the
mv
command. Renaming project files or folders using Finder may result in strange behaviour. See here for more details. -
There are some rare cases when breakpoints can’t be hit due to technical limitations, for example caused by the way how PHP generates bytecode. See here for more details.
When using Xdebug, you can use the xdebug_break()
function to force a breakpoint from within PHP. When Xdebug encounters this function during execution, it will pause at the next statement in the IDE even if no breakpoint was defined there originally.
Xdebug ignores a breakpoint and stops at a line where no breakpoint is defined
This can happen due to the Xdebug’s internal breakpoints resolving mechanism. Under this mechanism, the debugger evaluates whether PHP can generate internal executable bytecode for the current line. If no such code is generated for a line, the corresponding breakpoint cannot be hit. Xdebug will scan up to 5 subsequent lines, and stop at the line where executable code is located. Resolving breakpoints is supported in Xdebug 2.8 and later.
If necessary, you can configure breakpoints resolving support in PhpStorm on the page of the Settings dialog (Ctrl+Alt+S):
-
In the Xdebug area, use the Resolve breakpoint if it’s not available on the current line (Xdebug 2.8+) checkbox to toggle breakpoint resolving. Note that if resolving is disabled, the breakpoints set on the code lines without executable code will always be ignored.
-
In the Advanced settings area, use the Notify if breakpoint was resolved to a different line (Xdebug 2.8+) checkbox to choose whether PhpStorm should display a notification message when a breakpoint is resolved.
A script is not suspended
Establishing a Zero-Configuration debugging session may fail with no breakpoints hit and therefore the script not suspended. This may happen if the path mappings are not configured or configured erroneously, or if you have not set any breakpoints. In the latter case, you can do any of the following:
-
Set a breakpoint by clicking the gutter at the desired executable line of code. See Breakpoints for details.
-
In the Settings dialog (Ctrl+Alt+S), go to and in the External Connections area, select the Break at first line in PHP scripts checkbox.
-
Enable the option from the main menu.
To have PhpStorm display a notification if the script is not suspended, select the Notify if debug session was finished without being paused checkbox in the Advanced Settings area on the page of the Settings dialog.
The debugger does not work when using nginx
When using the nginx web server, debugging may fail if the $_SERVER["SERVER_NAME"]
is not provided by PHP. To solve this, add a fastcgi
parameter to the nginx configuration:
fastcgi_param SERVER_NAME $server_name;
or
fastcgi_param SERVER_NAME $host;
Refer to the nginx documentation and see here for additional details.
Xdebug cannot connect to PhpStorm
If you see the following messages in Xdebug log:
Log opened at 2017-02-21 17:52:27
I: Connecting to configured address/port: 172.19.0.1:9000.
W: Creating socket for ‘172.19.0.1:9000’, poll success, but error: Operation now in progress (29).
E: Could not connect to client. :disappointed:
Log closed at 2017-02-21 17:52:27
or
Log opened at 2017-02-22 13:17:13
I: Connecting to configured address/port: 10.10.10.10:9000.
E: Time-out connecting to client.
Log closed at 2017-02-22 13:17:14
This means that Xdebug tries to connect to the host and can’t make the connection. To fix the issue, set xdebug.remote_connect_back=0
(xdebug.discover_client_host=false
for Xdebug 3) and make sure that xdebug.remote_host
(xdebug.client_host
for Xdebug 3) is set correctly.
Trying to debug a framework CLI command results in PHP errors
When trying to debug a CLI command of a PHP framework command-line tool, such as Symfony Console or Laravel Artisan, debugging fails with a PHP error Fatal error: Class '...Command' not found"
or similar.
The common cause for such errors is attempting to debug the file or class with the command directly. Instead, you should use a PHP Script, in which you provide the path to the command-line tool and the actual command to run. In this case, the framework commands bootstrapping logic will apply, and debugging will proceed normally.
Refer to the following framework-specific guides for details:
-
Debugging Symfony CLI commands
-
Debugging Artisan CLI commands
-
Debugging WordPress WP-CLI commands
-
Debugging Drush CLI commands
Zend Debugger will not perform dropping of privileges
When using Zend Debugger on Linux, you may occasionally see the following error:
Zend Debugger: Cannot read a valid value of zend_debugger.httpd_uid or zend.httpd_uid, will not
perform dropping of privileges
This error occurs when the debugger cannot determine the UID of the user running the web server process. Find the UID of that user and add it to php.ini:
zend_debugger.httpd_uid=1234
After updating the setting, restart the web server.
Debugging with ionCube installed
In some PHP environments, ionCube is used to load and run the encoded PHP code. The ionCube loader extension does this by decoding the PHP code that is to be run and then making sure the PHP interpreter can execute it.
Officially, neither Xdebug nor Zend Debugger support running with ionCube enabled, however there are some workarounds to try. Note that these are not supported by JetBrains, ionCube, Xdebug or Zend Debugger.
-
Make sure the ionCube loader module is loaded first
In php.ini, verify the ionCube loader is loaded before any debugger extension is loaded, for example:
zend_extension=/usr/local/lib/php/extensions/no-debug-non-zts-20100525/ioncube_loader_lin_5.4.so
zend_extension=/usr/local/lib/php/extensions/no-debug-non-zts-20100525/xdebug.so -
Use ionCube on-demand loading
We can disable the ionCube extension in php.ini and make use of ionCube’s on-demand loading feature. When the first encoded PHP script is loaded, the PHP interpreter will check the configured
extenson_dir
to find the ionCube extension and run the encoded PHP script.Note that this method is not officially supported. It should only be used for debugging purposes and never on a production server.
Last modified: 16 September 2022
This post is more than 18 months old. Since technology changes too rapidly, this content may be out of date (but that’s not always the case). Please remember to verify any technical or programming information with the current release.
When PHP errors happen, often times there is an error log. This might be in the PHP error log itself or in a log file. For example, in one of my Laravel projects, I have two log files, one for errors and one for info or debug level information.
When errors happen remotely, most programmers will check the log file. However, when they happen during local development, we usually rely on seeing a unit test fail or a display that doesn’t match up. However, if you’re logging errors locally, you might forget to look at them. In my applications, I have the same level of logging locally as I have in production. This helps troubleshoot code issues that I might miss otherwise.
One of the things that can happen with PHP is that a certain level of error can happen (say a Warning type) but the script can continue. You might not even notice that something went wrong — if you’re not paying attention. For this reason, I’ve started using file watchers in PHPStorm to alert me of errors in my application log files.
PHPStorm file watchers typically are used to do things like compile javascript or SASS files automatically. However, any action can technically happen if there is an error.
The What
For our PHPStorm File Watcher, we want to watch our logs/error.log
file for any changes. If there are any changes, that means that an error happened. We might also notice the error on the screen or in our test. However, this watcher will provide a fallback for when we might not notice. The action it will display is to create a dialog or popup that let’s us know that there is a change to this file.
The How
First, you’ll need to install a terminal notifier application. For MacOS, I’d suggest terminal notifier (this is what I’m going to use for the demonstration). For Ubuntu/linux, you might use the notify-send
program.
Next, open PHPStorm.
Go to the Preferences...
menu item — this might be under the File
menu on Windows — or under the PHPStorm
menu on Mac.
In the search box, type watcher
which will bring up the Tools > File Watchers
dialog. Toward the bottom left hand of the main window dialog, click the +
to create a new file watcher. Choose custom
from the list.
In the new watcher, choose the following options as per the screenshot:
In order to make the scope, you’ll have to click the ...
link and create a new scope named error.log
— you can see the settings in the screenshot below:
Basically, what you do is to choose your error file and and include it. That will create the proper scope for your file watcher.
Save all the settings and you have a new alert system set up now. It’s a nice backup. Here’s an example of what you might see:
This section provides the list of solutions and workarounds for common problems with Debugging in PhpStorm.
Collecting PhpStorm debugging logs
If your issue is not addressed in this section, contact our support engineers. If asked to provide deployment logs, follow the instructions to collect them.
Collect debugging logs
-
Select in the main menu.
-
In the Custom Debug Log Configuration dialog that opens, add the following lines depending on the issues you are experiencing:
-
Issues with PHP debugging:
#com.jetbrains.php.debug
-
-
Click OK and reproduce the issue.
-
Locate the log file by selecting (for Windows and Linux) or (for macOS).
If necessary, you can locate the log manually:
- Syntax
- %HOMEPATH%.<product><version>systemlog
- Example
- C:UsersJohnS.PhpStorm2019.3systemlog
- Syntax
- ~/Library/Logs/<product><version>
- Example
- ~/Library/Logs/PhpStorm2019.3
- Syntax
- ~/.<product><version>/system/log
- Example
- ~/.PhpStorm2019.3/system/log
The most recent log file is named idea.log; older files names end with a number, that is idea.log.1, idea.log.2, and so on. In most cases you need only the most recent one.
-
Attach the log file(s) to the issue or forum thread.
Collecting Xdebug logs
When using Xdebug, it is possible to make it log its actions.
-
In the Settings/Preferences dialog Ctrl+Alt+S, select PHP under Languages & Frameworks.
-
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: <path to php.ini> file. Close all the dialogs and switch to the tab where the php.ini file is opened.
-
In the php.ini, enable
xdebug.remote_log
by adding the following line:xdebug.remote_log=path_to_log/xdebug.log
The log file contains the raw communication between PhpStorm and Xdebug as well as any warnings or errors:
Log opened at 2018-01-08 08:14:28 I: Connecting to configured address/port: 127.0.0.1:9000. I:
Connected to client. -> <init xmlns=»urn:debugger_protocol_v1″
xmlns:xdebug=»http://xdebug.org/dbgp/xdebug»
fileuri=»file:///C:/Projects/Samples/DebuggingTutorial/debugging.php» language=»PHP»
protocol_version=»1.0″ appid=»3040″ idekey=»11774″><engine version=»2.2.5″><![CDATA[Xdebug]]></engine><author><![CDATA[Derick
Rethans]]></author><url><![CDATA[http://xdebug.org]]></url><copyright><![CDATA[Copyright
(c) 2002-2018 by Derick Rethans]]></copyright></init><- step_into -i 5 -> <response xmlns=»urn:debugger_protocol_v1″
xmlns:xdebug=»http://xdebug.org/dbgp/xdebug» command=»step_into» transaction_id=»5″ status=»break»
reason=»ok»><xdebug:message
filename=»file:///C:/Projects/Samples/DebuggingTutorial/debugging.php» lineno=»2″></xdebug:message></response>
Making sure Xdebug or Zend Debugger are installed and configured
To debug PHP code with PhpStorm, make sure that you have a debugging engine, either Xdebug or Zend Debugger, installed and configured properly.
These tools cannot be used simultaneously because they block each other. To avoid this problem, you need to update the corresponding sections in the php.ini file as described in Configuring Xdebug and Configuring Zend Debugger.
To validate the debugging engine configuration, perform the steps described in Validating the Configuration of a Debugging Engine
Startup warnings and errors preventing the debugger from working
When running PHP, it can happen that a startup warning or error is displayed. When this is the case, the debugger may fail to work. PhpStorm will also not be able to recognize the debugger being used.
To verify that no startup warnings or errors are displayed, run the following command:
php —version
This will return a message similar to the following:
<some error/warning> PHP 7.1.20 (cli) (built: Jul 20 2018 10:27:12) ( NTS ) Copyright (c) 1997-2018
The PHP Group Zend Engine v3.1.0, Copyright (c) 1998-2018 Zend Technologies with Zend OPcache v7.1.20,
Copyright (c) 1999-2018, by Zend Technologies with Xdebug v2.6.0, Copyright (c) 2002-2018, by Derick Rethans
If any errors or warnings are present on the first lines, it’s recommended to fix them before continuing.
The debugger cannot connect
When the debugger cannot connect or refuses the connection, check the following:
-
Make sure Xdebug or Zend Debugger are configured to connect to the host and port PhpStorm is running on.
-
In the Xdebug configuration, make sure
xdebug.remote_host
andxdebug.remote_port
are correct. Refer to the Xdebug documentation for details. -
When using Zend Debugger, make sure the generated PhpStorm bookmarklets or a Browser Debugging Extension is configured to use the correct IP address and port.
-
When using a remote PHP interpreter, verify the steps outlined in Remote debugging via SSH tunnel.
-
-
In the Settings/Preferences dialog Ctrl+Alt+S, navigate to and make sure PhpStorm and Xdebug / Zend Debugger are configured with the same port numbers.
-
In PhpStorm, enable listening to incoming debug connections by either clicking on the toolbar or selecting in the main menu. This will ensure PhpStorm reacts when a debugging session is started and opens the Debug tool window automatically. Before launching the script, make sure that either a breakpoint is set or the Break at first line in PHP scripts option is enabled on the Debug page of the Settings/Preferences dialog Ctrl+Alt+S.
-
Verify no firewall, router or ISP is blocking the connection. This can be verified by running
telnet host 9000 (for Xdebug)
ortelnet host 10137
(for Zend Debugger) from remote server (where host is an IP address of your local machine running PhpStorm) and checking a connection is established. You can use http://www.canyouseeme.org or a similar service to check for opened inbound ports. -
Make sure that
xdebug.remote_host
(for Xdebug) orzend_debugger.allow_hosts
(for Zend Debugger) are properly configured. The value can be a host name (for example, localhost) or an IP address of the machine where PhpStorm is running, and it must be pingable from the server. When using Xdebug, xdebug.remote_connect_back can be used for troubleshooting.
Remote file path is not mapped to any file path in project
In some cases, the debugger can connect, but we get the error messages indicating that no mapping between the remote and project files is defined. This means that PhpStorm cannot determine which local file corresponds to the file being debugged.
We can solve this problem by clicking Click to set up path mappings and providing the necessary path mappings.
Path mappings are used when the paths to the files processed by the server differ from the paths to the files in the PhpStorm project. This happens in the following cases:
-
The server is remote and the project files are local copies of the originals.
-
The files processed by the server and the files opened in the IDE are the same, but symlinks are used. Because the debugger resolves symlinks during a debugging session, you need to tell the IDE actual solute physical paths to the files on the server.
To configure path mappings, in the Settings/Preferences dialog Ctrl+Alt+S, navigate to .
If the files that the server processes are in the project and you are not using symlinks, clear the Use path mappings checkbox. In this case, the IDE will open files according to the paths received from the debugger.
A path mapping specified for a parent directory is automatically applied to all its subdirectories. If necessary, path mappings for any subdirectory or file can be specified.
See Configuring Synchronization with a Web Server for more details.
Breakpoints are not being hit
When breakpoints are not being hit but the debugger seems to connect, verify the following:
-
Verify the breakpoint is not disabled. Using the menu command (Ctrl+Shift+F8 ), check that breakpoints are enabled. Select the checkbox next to a breakpoint to enable it.
-
Make sure that path mappings are correct .
-
On macOS, when a file or folder is renamed using Finder, and the letter case is changed, PhpStorm may not be able to find the files. If renaming is required, make sure to do it in the IDE or using a terminal and the
mv
command. Renaming project files or folders using Finder may result in strange behaviour. See here for more details. -
There are some rare cases when breakpoints can’t be hit due to technical limitations, for example caused by the way how PHP generates byte-code. See here for more details.
When using Xdebug, you can use the xdebug_break()
function to force a breakpoint from within PHP. When Xdebug encounters this function during execution, it will pause at the next statement in the IDE even if no breakpoint was defined there originally.
The debugger does not work when using nginx
When using the nginx web server, debugging may fail if the $_SERVER["SERVER_NAME"]
is not provided by PHP. To solve this, add a fastcgi
parameter to the nginx configuration:
fastcgi_param SERVER_NAME $server_name;
or
fastcgi_param SERVER_NAME $host;
Refer to the nginx documentation and see here for additional details.
Xdebug cannot connect to PhpStorm
If you see the following messages in Xdebug log:
Log opened at 2017-02-21 17:52:27
I: Connecting to configured address/port: 172.19.0.1:9000.
W: Creating socket for ‘172.19.0.1:9000’, poll success, but error: Operation now in progress (29).
E: Could not connect to client. :disappointed:
Log closed at 2017-02-21 17:52:27
or
Log opened at 2017-02-22 13:17:13
I: Connecting to configured address/port: 10.10.10.10:9000.
E: Time-out connecting to client.
Log closed at 2017-02-22 13:17:14
This means that Xdebug tries to connect to the host and can’t make the connection. To fix the issue, set xdebug.remote_connect_back=0
and make sure that xdebug.remote_host
is set correctly.
Trying to debug a framework CLI command results in PHP errors
When trying to debug a CLI command of a PHP framework command-line tool, such as Symfony Console or Laravel Artisan, debugging fails with a PHP error Fatal error: Class '...Command' not found"
or similar.
The common cause for such errors is attempting to debug the file or class with the command directly. Instead, you should use a Run/Debug Configuration: PHP Script, in which you provide the path to the command-line tool and the actual command to run. In this case, the framework commands bootstrapping logic will apply, and debugging will proceed normally.
Refer to the following framework-specific guides for details:
- Debugging Symfony CLI commands
- Debugging Artisan CLI commands
- Debugging WordPress WP-CLI commands
- Debugging Drush CLI commands
Zend Debugger will not perform dropping of privileges
When using Zend Debugger on Linux, you may occasionally see the following error:
Zend Debugger: Cannot read a valid value of zend_debugger.httpd_uid or zend.httpd_uid, will not
perform dropping of privileges
This error occurs when the debugger cannot determine the UID of the user running the web server process. Find the UID of that user and add it to php.ini:
zend_debugger.httpd_uid=1234
After updating the setting, restart the web server.
Debugging with ionCube installed
In some PHP environments, ionCube is used to load and run the encoded PHP code. The ionCube loader extension does this by decoding the PHP code that is to be run and then making sure the PHP interpreter can execute it.
Officially, neither Xdebug nor Zend Debugger support running with ionCube enabled, however there are some workarounds to try. Note that these are not supported by JetBrains, ionCube, Xdebug or Zend Debugger.
-
Make sure the ionCube loader module is loaded first
In php.ini, verify the ionCube loader is loaded before any debugger extension is loaded, for example:
zend_extension=/usr/local/lib/php/extensions/no-debug-non-zts-20100525/ioncube_loader_lin_5.4.so
zend_extension=/usr/local/lib/php/extensions/no-debug-non-zts-20100525/xdebug.so -
Use ionCube on-demand loading
We can disable the ionCube extension in php.ini and make use of ionCube’s on-demand loading feature. When the first encoded PHP script is loaded, the PHP interpreter will check the configured
extenson_dir
to find the ionCube extension and run the encoded PHP script.Note that this method is not officially supported. It should only be used for debugging purposes and never on a production server.
Last modified: 29 November 2019
Всё ещё отлаживаете PHP по-старинке? Рассказываем про инструмент, которым пользуются современные PHP-программисты. Этот инструмент – Xdebug.
Конечно, можно отлаживать PHP-код используя простые функции вроде error_log, print_r и var_dump, но они не позволяют отслеживать процесс работы кода. Для этого PHP-разработчики используют Xdebug. В данной статье рассказываем, почему это удобно, как использовать и облегчить процесс отладки.
Многие из тех, кто не знаком с Xdebug, используют для отладки функцию, которую часто упоминают на Stack Overflow:
if ( ! function_exists( '_log' ) ) { function _log( $message ) { if ( WP_DEBUG === true ) { if ( is_array( $message ) || is_object( $message ) ) { error_log( print_r( $message, true ) ); } else { error_log( $message ); } } } }
Когда вы отлаживаете с использованием error_log, не всегда выводятся те переменные, которые требуются. Например, в процессе устранения ошибок вы добавляете функцию для отладки переменной, обновляете страницу, проверяете лог ошибок. Если установить, в чём ошибка, не удается, приходится повторять процесс снова и снова.
Xdebug позволяет останавливать процесс во время его исполнения и проверять переменные. Это означает, что у вас есть все необходимое для устранения неполадок во время одной итерации этого цикла. Такая функция помогает сделать процесс разработки более эффективным.
Устранение проблем с использованием Xdebug
Брейкпоинты Xdebug позволяют останавливать исполнение кода в любой момент. Это значит, что можно перемещать брейкпоинты, пока не обнаружится область, откуда исходит проблема.
Разработка через тестирование
Еще одна область применения Xdebug – Debug Driven Development, позволяющая быстро решать проблемы. Вот как это можно делать через Xdebug:
- Проверьте существующие массивы, объекты и экземпляры классов, чтобы найти фрагменты кода, которые можно использовать несколько раз.
- Отлаживайте новые фрагменты и проверяйте, нет ли ошибок.
Это необязательно использовать часто, но сам факт наличия такой функции уже радует.
Установка Xdebug
Даже если преимущества не кажутся существенными, попробовать Xdebug точно стоит. Вот несколько самых распространённых сред:
- MAMP
- MAMP Pro
- VVV
- Local By Flywheel
- Valet
- Desktop Server
Интеграция с PHPStorm
Многим нравится PhpStorm. У него есть интеграция с Xdеbug, и настроить их совместную работу достаточно просто. Но есть и другие редакторы и интегрированные среды разработки (IDE) с поддержкой Xdebug.
Начало отладки
После установки и настройки интеграций можно начинать отладку кода. Это делается путем установки брейкпоинтов на определенных строках вашего кода и указания PHPStorm начать отслеживать входящую информацию. Когда PHP начнёт выполнять строку с брейкпоинтом, Xdebug включится в работу и позволит узнавать подробности в процессе выполнения.
На боковой панели отладки имеются различные кнопки для управления исполнением кода (иконки слева). Вот как они работают:
- Resume Program – продолжение выполнения PHP-кода.
- Pause Program – недоступна во время отладки.
- Stop – остановка выполнения.
- View Breakpoints – открытие списка брейкпоинтов всего проекта.
- Mute Breakpoints – отключение брейкпоинтов в процессе выполнения (полезно, если проблема уже найдена, а процесс ещё не закончен).
- Restore Layout – сброс настроек панели отладки.
- Settings – настройка отображения отладчика.
- Pin Tab – всегда показывает панель отладки.
- Close – закрытие панели, возможность отключения соединения или полного завершения.
- Help – справки по работе панели от JetBrains.
Верхняя панель управляет тем, как происходит отладка кода:
- Show Execution Point – переход к ошибке.
- Step Over – выполнение и переход к следующей строке.
- Step Into – если в следующей строке есть одна или несколько функций, отладчик приступит к следующим функциям в строке.
- Force Step Into – переход к функции, отмеченной как пропущенная.
- Step Out – отправка отладчика к функции вызова.
- Run to Cursor – исполнения до момента, где находится курсор мышки.
- Evaluate Expression – выполнение PHP-кода во время работы отладчика.
- Show Values Addresses – отображение адреса памяти объектов.
- Hide Empty Superglobals Variables – удаление лишнего из списка переменных.
- Add Method to Skip List – отмечает метод, который будет пропущен в следующий раз.
PhpStorm позволяет добавлять переменные в список, который отображается на панели «Watches». Вы можете просмотреть переменную, щелкнув правой кнопкой мыши по её файлу в процессе отладки и выбрав «Add to Watches», либо сделав то же самое на панели «Variables».
Трассировка стека
Включение Xdebug дает вам по умолчанию расширенную трассировку стека для любых ошибок, уведомлений или предупреждений, которые записываются в журнал PHP:
[26-Jul-2017 16:06:21 UTC] PHP Notice: Trying to get property of non-object in /Applications/MAMP/htdocs/deliciousbrains.com/public_html/content/themes/deliciousbrains/functions.php on line 302 [26-Jul-2017 16:06:21 UTC] PHP Stack trace: [26-Jul-2017 16:06:21 UTC] PHP 1. {main}() /Applications/MAMP/htdocs/deliciousbrains.com/public_html/index.php:0 [26-Jul-2017 16:06:21 UTC] PHP 2. require() /Applications/MAMP/htdocs/deliciousbrains.com/public_html/index.php:3 [26-Jul-2017 16:06:21 UTC] PHP 3. require_once() /Applications/MAMP/htdocs/deliciousbrains.com/public_html/wp/wp-blog-header.php:19 [26-Jul-2017 16:06:21 UTC] PHP 4. include() /Applications/MAMP/htdocs/deliciousbrains.com/public_html/wp/wp-includes/template-loader.php:74 [26-Jul-2017 16:06:21 UTC] PHP 5. get_header($name = *uninitialized*) /Applications/MAMP/htdocs/deliciousbrains.com/public_html/content/themes/deliciousbrains/404.php:2 [26-Jul-2017 16:06:21 UTC] PHP 6. locate_template($template_names = *uninitialized*, $load = *uninitialized*, $require_once = *uninitialized*) /Applications/MAMP/htdocs/deliciousbrains.com/public_html/wp/wp-includes/general-template.php:45 [26-Jul-2017 16:06:21 UTC] PHP 7. load_template($_template_file = *uninitialized*, $require_once = *uninitialized*) /Applications/MAMP/htdocs/deliciousbrains.com/public_html/wp/wp-includes/template.php:647 [26-Jul-2017 16:06:21 UTC] PHP 8. require_once() /Applications/MAMP/htdocs/deliciousbrains.com/public_html/wp/wp-includes/template.php:688 [26-Jul-2017 16:06:21 UTC] PHP 9. do_action($tag = *uninitialized*, $arg = *uninitialized*) /Applications/MAMP/htdocs/deliciousbrains.com/public_html/content/themes/deliciousbrains/header.php:27 [26-Jul-2017 16:06:21 UTC] PHP 10. WP_Hook->do_action($args = *uninitialized*) /Applications/MAMP/htdocs/deliciousbrains.com/public_html/wp/wp-includes/plugin.php:453 [26-Jul-2017 16:06:21 UTC] PHP 11. WP_Hook->apply_filters($value = *uninitialized*, $args = *uninitialized*) /Applications/MAMP/htdocs/deliciousbrains.com/public_html/wp/wp-includes/class-wp-hook.php:323 [26-Jul-2017 16:06:21 UTC] PHP 12. dbi_theme_body(*uninitialized*) /Applications/MAMP/htdocs/deliciousbrains.com/public_html/wp/wp-includes/class-wp-hook.php:298 [26-Jul-2017 16:06:21 UTC] PHP 13. dbi_theme_render_part($part = *uninitialized*, $args = *uninitialized*) /Applications/MAMP/htdocs/deliciousbrains.com/public_html/content/themes/deliciousbrains/functions.php:137 [26-Jul-2017 16:06:21 UTC] PHP 14. include() /Applications/MAMP/htdocs/deliciousbrains.com/public_html/content/themes/deliciousbrains/functions.php:11 [26-Jul-2017 16:06:21 UTC] PHP 15. dbi_theme_is_products_page() /Applications/MAMP/htdocs/deliciousbrains.com/public_html/content/themes/deliciousbrains/parts/nav/nav.php:15 [26-Jul-2017 16:06:21 UTC] PHP 16. dbi_theme_is_product_page($product = *uninitialized*) /Applications/MAMP/htdocs/deliciousbrains.com/public_html/content/themes/deliciousbrains/functions.php:315
Расширенная трассировка стека полезна сама по себе, но вместе с PhpStorm можно посмотреть интерактивную историю того, какой код был выполнен до брейкпоинта или текущей точки выполнения.
Заключение
Используя Xdebug, можно неплохо сэкономить время. Многие даже не могут представить жизнь без этого инструмента.
Если вы знаете ещё более крутой отладчик или можете рассказать о классных вещах, которые помог вам сделать Xdebug, пишите в комментариях.
Понравилась статья? Посмотрите нашу подборку материалов по PHP 7.
Источник: Deliciousbrains