Use xdebug to debug PHP programs in eclipse

Source: Internet
Author: User
Tags php server php debugger


debugging software is not exactly a fun job for developers. the most widely used Debugger for PHP still seems to be avar_dump ()statement, possibly in conjunction withdie ()to halt program execution at a certain point. while there is nothing wrong usingvar_dump ()statements in itself, you still need to change the program code to debug a PHP script. and worse, after you have finished debugging, you must remove allvar_dump ()statements again (well you should, at least ). it may well be that a few days later you'll find yourself adding the very samevar_dump ()statements to your code again because you need to go hunting another bug.



Of course, You coshould just comment out thevar_dump ()statements, but that looks really ugly in the code. another option wocould be to wrap thevar_dump ()In conditional clses, and only execute them when, say, A constantdebugis defined. this affects performance, because even if thevar_dump ()statements are not executed, the conditional clause must be executed. and besides, it looks even uglier in the code.



as we have already learned in the second articles of this series, having xdebug 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 necessary for the debugging process, so using a debugger is a much better solution. a debugger allows you to pause program execution at any time, inspect or modify the current variable values, and then continue the program. by executing a program step by step, you can closely watch the code doing its job, which hopefully helps you to find out quickly where things go wrong.



BeyondVar_dump, Debugging in PHP has been problematic for a long time, at least if you were not willing to spend money on a too cial ide that supports debugging. with xdebug, open source debugging of PHP code has-in theory-been possible for quite a while now. I say theoretically because until recently 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-platform xdebug 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 with debugging.


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 is present. if you have no Java Runtime Environment installed on your computer, you can download your copy from www.sun.com.



You can download a ready-to-go-package of eclipse PDT from http://www.eclipse.org/pdt. you shoshould choose the appropriate version for your platform, though all packages are basically only compressed archives of the necessary files to run eclipse. still, the Windows version comes with. ExeFile that starts eclipse, which is way more user-friendly than calling the Java classes directly.



As I write this article, the current release build version of eclipse PDT is r20070917. choose the latest available version and have some coffee ready, because the eclipse PDT download is over 100 MB in size. but since it is a Java application, having a nice cup of coffee while you wait for the download to complete shoshould 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 us have a look at how PHP debugging with xdebug actually works. This will help you better understand the 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 resume program execution at any time. when program execution is paused, xdebug can retrieve information about the current program state, like reading variable values. it is even possible for xdebug to change the value of a variable, then continue the script execution with a modified value.



The xdebug extension is a server, expecting client connections at a certain retriable port. there are two protocols that can be used to communicate between the xdebug client and the xdebug server, GDB and dbgp. GDB is an older Protocol, which has been superceded by dbgp. by sending commands to the xdebug server, the xdebug client acts as a sort of remote control for PHP, telling PHP to pause execution, execute one step, 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 debug Protocol itself.



The PHP server with xdebug can run on a another system than the one running the xdebug client. that is why xdebug is called a remote debugger. for simplicity, we will set 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 settingxdebug. remote_mode. the default setting is req , which makes xdebug always connect to the debug client when a script is started. if you want xdebug to only connect to the debug client on a breakpoint or an error in the script, you can setxdebug. remote_modeto JIT . I wocould recommend keeping the default setting, which you can achieve by putting noxdebug. remote_modesetting into PHP. INI .



To actually start a debug session, you must pass a parameterXdebug_session_startTo the script by get, post, or cookie. the value of this parameter is the debug session name, which shoshould be unique at a given point in time, so that xdebug can distinguish different debug sessions running concurrently. to end a debug session, you need to passXdebug_session_stopTo the script.



Instead of manually dealing with the starting and stopping of DEBUG sessions, you can install a Firefox plugin that allows you to conveniently start and stop a debug session with a mouse click.



Using eclipse PDT, you will not even have to worry about the browser plugin, 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 to worry about, because eclipse sets it for you.


Using ing xdebug


Now let us configure xdebug debugging. Add the following settingsPHP. ini:





 

Xdebug. remote_enable = on
Xdebug. remote_host = "localhost"
Xdebug. remote_port = 9000
Xdebug. remote_handler = "dbgp"


Make sure you add these lines afterZend_extension_tsLine that loads the xdebug extension. The first entry enables the debugger. The second entry defines that the debug client runs onLocalhost-This coshould be any valid DNS name or IP address, if the client and the server were not on the same computer.



The third setting defines the port the xdebug server expects the client to 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 no compelling reason to do otherwise, you shoshould keep the default port. if you want to change the port, keep in mind that you have to configure the same port number in eclipse andPHP. ini.



Also, make sure that no firewall gets into your way. when you start eclipse, you might see a warning that Java is trying to set up a server, bind to a port, access the network, or perform some obscure potentially dangerous action. of course, it's not dangerous, it's just the xdebug client trying to listen port 9000. if you have problems with debugging, check if there are any firewils between the debug server and the debug client that might block port 9000.



Last but not least, we have to tell xdebug which Protocol the client speaks. Eclipse PDT speaks dbgp, so you may not change this setting.


Using ing eclipse PDT


To configure eclipse PDT, start eclipse by double-clicking the eclipse executable. Create a New PHP project. Let us name the projectDebug_test. Now, create a fileDebug. phpIn the project, add some code, then save the file.



Now let us configure eclipse for debugging with xdebug. first of all, we will configure eclipse to launch projects in an external browser instead of its internal browser. when an external browser is configured, all debugging sessions will be launched in an external browser as well. using an external browser is not absolutely necessary, but I prefer to work with Firefox instead of Eclipse's internal browser. chooseWindowFrom the menu bar, then selectPreferences(See the following screenshot). ExpandGeneralSubtree, and clickWeb Browser. Now, select the radio buttonUse external browserAnd clickApply.






Eclipse PDT supports the Zend debugger and xdebug. By default, the Zend debugger is activated. To change this setting to xdebug, expandPHPSubtree andDebugSubtreePHP. Then, changePHP DebuggerToXdebugAnd clickApply.



Now, chooseRunFrom the menu bar and click the entryOpen debug Dialog. Then, double clickPHP Web PageTo create a new debug configuration.



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 the script 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_test directory.



Eclipse needs to know the URL matching the script filename and path you just entered. This is required to highlight the currently executed line in the source code.URLText Field shows the URL that is mapped to the filename. By default,URLText field deactivated becauseAuto generateCheckbox is activated. If the displayed URL does not match the URL you wocould type into your browser to see the script you have specified inFile/Project, UncheckAuto generateAnd enter the correct URL inURLText field. If THG script to debug requires any get parameters, You can append them to the URL given here.



Do not forget to clickApplyTo save the changes. The following screenshot shows how the debug configuration looks like on my system:






Change toAdvancedTab and make sure thatOpen in browserAnd the radio buttonDebug all pagesBoth are checked. Now you can close the Configuration window and start a debugging session.


Debugging a PHP script


To start debugging a PHP script, chooseRunFrom the menu bar and selectDebug. You can just cut this by pressing the F11 key. eclipse will ask you wether you want to open the debug view. you shoshould 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 myDebug. phpScript (which contains some pointless code ):






eclipse has opened your system's default browser (or whatever browser you have configured it to open ). you will not see output in the browser window yet, because eclipse by default pauses script execution on the first line of the script, as if a breakpoint were set on this line. if you want to disable this behaviour, uncheck the break at first line checkbox in the breakpoint section from the debug dialog Configuration window.



as the screenshot shows, you can see the source code of the debugged file, 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 are valid in every scope, so they are always displayed. the breakpoints tab lets you view and edit all breakpoints in your 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 is reached, execute just one step, or step into the next function, or out of the next function scope by clicking the appropriate icons inDebugTop 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 see the variable values change with each step.


Changing variables at runtime


You can even change variable values during script runtime. while this does not really fix a bug, it might be useful to provoke certain errors without modifying the source code. to change a variable, click the current value, modify it and pressEnter.


Breakpoints


a breakpoint pauses script execution and allows you to inspect variable values, then continue the program. the program execution is also paused if an exception occurs in your PHP code. to set a breakpoint, right-click a line number in the source code, then choose toggle breakpoints from the context menu. you can remove breakpoints in the same way, or remove them in the breakpoints tab by right-clicking a breakpoint and selecting remove from the context menu.



you can even add a condition to a breakpoint. conditional breakpoints will only pause the program execution when the given condition is met. this is can be very useful when the same piece of code is executed multiple times with different parametrization. to add a condition to a breakpoint, right-click the breakpoint icon to the left of the line number in the source code view. choose breakpoint properties . you can remove conditions in the same way or by right-clicking a breakpoint and selecting set condition from the context menu in the breakpoints tab.



CheckEnable Set ConditionAnd enter a condition in PHP code into the text field. In myDebug. php, The FunctionTest ()Is called on line 11 and a breakpoint is set on this line. By adding the condition$! =''Xdebug will only Pause program execution on this line when the local variable$Is non-empty at the time the breakpoint is reached.



To end a debugging session, highlightRemote launchIn the top left pane, then clickTerminateIcon which is located betweenRunAnd the variousStepIcons. If you had eclipse run the script in an external browser, you need to close the browser window manually.


Conclusion


remote debugging is a great interactive and non-intrusive way of finding bugs in your PHP scripts. instead of puttingvar_dump ()statements into your code, or working your way through a long trace log including parameter and return values, debugging gives you a macrosopic view of critical areas in your code.


Related Article

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.