Eclipse用XDebug调试PHP程序
Debugging software is not exactly a fun job for developers. The most widely used debugger for PHP still seems to be a var_dump() statement, possibly in conjunction with die()to halt program execution at a certain point. While there is nothing wrong using var_dump() statements initself, you still need to change the program code to debug a PHP script. And worse,after you have finished debugging,you must remove all var_dump() statements again (well youshould, at least). It may well be that a few days later you'll find yourself adding thevery same var_dump() statements to your code again because you need to go hunting anotherbug.Of course, you could just comment out the var_dump()statements, but that looks really ugly in the code. Another option would be to wrap the var_dump() inconditional clauses, and only execute them when, say, a constant DEBUG is defined. This affects performance, because even if the var_dump()statements are not executed, the conditional clause must be executed. And besides, it looks evenuglier in the code.
As we have already learned in the second articles of this series, havingxdebug create a trace log might be a better option in this case,because you do not have to change the program code. But a trace log, even if only created for a part of the application,provides us with a lot of information that may not be necessaryfor the debugging process, so using a debugger is a much bettersolution. A debugger allows you to pause program execution at any time, inspect ormodify the current variable values, and then continue the program.By executing a program step by step, you can closely watch the codedoing its job, which hopefully helps you to find out quickly where things go wrong.
Beyond var_dump, debugging in PHP has been problematic for along time, at least if you were not willing to spend money on a commercial IDE thatsupports debugging. With xdebug, open source debugging of PHP code has - in theory - been possible for quite a while now. I say theoretically because untilrecently no good and free debug client for xdebug was available for both Windows and Unix.
This fall, the problem of having no release-quality cross-platformxdebug client has been solved with the release of Eclipse PDT. Eclipse PDT is a free IDE for PHP supporting xdebug out of the box. So, without further ado, let us install Eclipse PDT to get started withdebugging.
Installing Eclipse PDT
Eclipse PDT (PDT is short for PHP Development Tools) is written in Java, and thus works on most platforms where a Java Runtime Environment ispresent. If you have no Java Runtime Environment installed on your computer, youcan download your copy fromwww.sun.com.
You can download a ready-to-go-package of Eclipse PDT fromhttp://www.eclipse.org/pdt. Youshould choose the appropriate version for your platform, though all packagesare basically only compressed archives of the necessary files to run eclipse. Still, the Windows version comes with an .exe file that startsEclipse, whichis way more user-friendly than calling the Java classes directly.
As I write this article, the current Release Build version of EclipsePDT is R20070917. Choose the latest available version and have some coffee ready, because the Eclipse PDT download is over 100 MB in size. Butsince it is a Java application, having a nice cup of coffee while you wait forthe download to complete should be suitable. Once the download has completed, unpack the downloaded archive and you are ready to start Eclipse PDT.
How debugging works
Before we get into the configuration of xdebug and Eclipse PDT, let ushave a look at how PHP debugging with xdebug actually works. This will help youbetter understandthe configuration described below.
When debugging is enabled in php.ini, xdebug controls the program execution in PHP, which basically means that xdebug can pause and resumeprogram execution at any time. When program execution is paused, xdebug can retrieveinformation about the current program state, like reading variable values. It is evenpossible for xdebug tochange the value of a variable, then continue the script execution with amodified value.
The xdebug extension is a server, expecting client connections at acertain configurable port. There are two protocols that can be used to communicate between thexdebug client and the xdebug server, GDB and DBGp. GDB is an older protocol, which hasbeen superceded byDBGp. By sending commands to the xdebug server, the xdebug client actsas a sort ofremote control for PHP, telling PHP to pause execution, execute onestep, or to continue the program execution. The client is usually embedded into an editor or the IDE (in our case, into Eclipse PDT), so you will not have to deal with the debugprotocol itself.
The PHP server with xdebug can run on a another system than the onerunning the xdebug client. That is why xdebug is called a remote debugger. For simplicity, we willset up the debugging server and client on the same computer.
There are two different modes of starting a debug session with xdebug.They are controlled by the php.ini setting xdebug.remote_mode. The defaultsetting is req, which makes xdebug always connect to the debug client when a script isstarted. If you want xdebugto only connect to the debug client on a breakpoint or an error in thescript, you can setxdebug.remote_mode to jit. I would recommend keepingthe default setting,which you can achieve by putting no xdebug.remote_modesetting into php.ini.
To actually start a debug session, you must pass a parameter XDEBUG_SESSION_START to the script by GET, POST, or cookie. The value of this parameter isthe debug session name, which should be unique at a given point in time, so that xdebug can distinguishdifferent debug sessions running concurrently. To end a debug session, you need to pass XDEBUG_SESSION_STOPto the script.
Instead of manually dealing with the starting and stopping of debugsessions, you can install a firefoxpluginthat allows you to conveniently start and stop a debug session with amouse click.
Using Eclipse PDT, you will not even have to worry about the browserplugin, as the IDE takes care of passing the appropriate parameters to the browser.xdebug also requires setting of a IDE key, which you also do not have toworry about, because Eclipse sets it for you.
Configuring xdebug
Now let us configure xdebug debugging. Add the following settings to php.ini:
xdebug.remote_enable=On
xdebug.remote_host="localhost"
xdebug.remote_port=9000
xdebug.remote_handler="dbgp"
Make sure you add these lines after the zend_extension_tsline that loads the xdebug extension. The first entry enables the debugger. The second entry defines that the debug client runs on localhost- this could be any valid DNS name or IP address, if the client and the server werenot on the same computer.
The third setting defines the port the xdebug server expects the clientto listen on (which, strictly speaking, makes the client a server, but let us not get confused about this).By default, the port is 9000.This port is configured in Eclipse by default, and if there is nocompelling reason to do otherwise,you should keep the default port. If you want to change the port, keepin mind that you have to configure the same port number in Eclipse and php.ini.
Also, make sure that no firewall gets into your way. When you startEclipse, you might see a warning that Java is trying to set up a server, bind to a port, accessthe network, or perform some obscure potentially dangerous action. Of course, it's not dangerous, it's justthe xdebug client trying to listen at port 9000. If you have problems with debugging, check if there are any firewallsbetween the debug server and the debug client that might block port 9000.
Last but not least, we have to tell xdebug which protocol the clientspeaks. Eclipse PDT speaks DBGp, so you may not change this setting.
Configuring Eclipse PDT
To configure Eclipse PDT, start Eclipse by double-clicking the Eclipseexecutable.Create a new PHP project. Let us name the project debug_test. Now, create a file debug.php in the project, add some code, thensave the file.
Now let us configure Eclipse for debugging with xdebug. First of all, we will configure Eclipse to launch projects in an external browserinstead of its internal browser. When an external browser is configured, all debugging sessionswill be launched in an external browser as well. Using an external browser is not absolutely necessary, but I prefer towork with Firefox instead of Eclipse's internal browser. Choose Window from the menu bar, then select Preferences(see the following screenshot). Expand the General subtree,and click Web Browser. Now, select the radio button Useexternal browserand click Apply.
http://devzone.zend.com/images/articles/2930/eclipse_preferences.jpg
Eclipse PDT supports the Zend debugger and xdebug. By default, the Zenddebugger is activated. To change this setting to xdebug, expand the PHPsubtree and the Debug subtree of PHP. Then, change PHP debugger to Xdebug and click Apply.
Now, choose Run from the menu bar and click the entry OpenDebug Dialog. Then, double click PHP Web Page to create a new debugconfiguration.
You will see a window with three tabs, Server, Advanced,and Common. When not already selected, choose Xdebug as Server Debugger. In the File / Project text field, you must enter the path to thescript you want to debug.This path must be relative to your workspace. On my system, this is /debug_test/debug.php. Click Browse and select the file debug.php in the debug_testdirectory.
Eclipse needs to know the URL matching the script filename and path youjust entered. This is required to highlight the currently executed line in the source code.The URL text field shows the URL that is mapped to the filename. By default, the URL text field deactivated because the AutoGenerate checkbox is activated. If the displayed URL does not match the URL you would type into yourbrowser to see the script you have specified in File / Project, uncheck Auto Generate and enter thecorrect URL in the URL text field. If thg script to debug requires any GET parameters, you can append themto the URL given here.
Do not forget to click Apply to save the changes. The following screenshot shows how the debug configuration looks like onmy system:
http://devzone.zend.com/images/articles/2930/eclipse_debug_config.jpg
Change to the Advanced tab and make sure that Open in Browserand the radio buttonDebug All Pages both are checked. Now you can close the configuration window and start a debuggingsession.
Debugging a PHP script
To start debugging a PHP script, choose Run from the menu bar andselectDebug. You can shortcut this by pressing the F11 key. Eclipsewill ask you wether you want to open the debug view. You should tick the checkbox to remember this setting,otherwise you will be asked the same question every time you start debugging.
The following screenshot shows Eclipse's debug view of my debug.phpscript (which contains some pointless code):
http://devzone.zend.com/images/articles/2930/eclipse_debug.jpg
Eclipse has opened your system's default browser (or whatever browseryou have configured it to open).You will not see output in the browser window yet, because Eclipseby default pauses script execution on the first line of the script, asif a breakpoint were set on this line. If you want to disable this behaviour, uncheckthe Break at First Line checkbox in the Breakpoint sectionfrom the debug dialog configuration window.
As the screenshot shows, you can see the source code of the debuggedfile, with the currently executed line marked with an arroq to the left of the line number.In the above right area, you can choose between different tabs. The Variables tab shows the current values of all variables in the current scope. The superglobal variables arevalid in every scope, so they are always displayed. The Breakpoints tab lets you view and edit all breakpoints inyour script. Eclipse will remember any breakpoints you have set on the code, even if you close and restart Eclipse.
You can now continue program execution until the next breakpoint isreached, execute just one step, or step intothe next function, or out of the next function scope by clicking theappropriate icons in the Debugtop left area of the window. Stepping is useful when you have located the problem area in your code and want to watch closely what is happening. You will seethe variable values change with each step.
Changing Variables at Runtime
You can even change variable values during script runtime. While thisdoes not really fix a bug, itmight be useful to provoke certain errors without modifying the sourcecode. To change a variable, click the current value, modify it and press Enter.
Breakpoints
A breakpoint pauses script execution and allows you to inspect variablevalues, then continue the program.The program execution is also paused if an exception occurs in your PHPcode. To set a breakpoint, right-click a line number in the source code, thenchoose Toggle Breakpoints fromthe context menu. You can remove breakpoints in the same way, or removethem in the Breakpoints tab by right-clicking a breakpoint and selecting Remove from thecontext menu.
You can even add a condition to a breakpoint. Conditional breakpointswill only pause the program execution when the given condition is met. This is can be very useful when the same pieceof code is executed multiple times with different parametrization. To add a condition to a breakpoint, right-click the breakpoint icon tothe left of the line number inthe source code view. Choose Breakpoint Properties.You can remove conditions in the same way or by right-clicking abreakpoint andselecting Set Condition from the context menu in the Breakpointstab.
Check Enable Set Condition and enter a condition in PHP code intothe text field. In my debug.php,the function test() is called on line 11 and a breakpointis set on this line. By adding the condition $a != '' xdebug will only pause program execution on thisline when the local variable $a is non-empty at the time the breakpoint is reached.
To end a debugging session, highlight Remote Launch in the topleft pane, then click the Terminate icon which islocated between the Run and the various Step icons. If youhad Eclipse run the script in an externalbrowser, you need to close the browser window manually.
Conclusion
Remote debugging is a great interactive and non-intrusive way of findingbugs in your PHP scripts. Instead of putting var_dump() statements into your code, or working your way through a long trace logincluding parameter and return values, debugging gives you a macrosopic view of critical areas in your code.
页:
[1]