IT Community - Software Programming, Web Development and Technical Support

Debugging techniques in PHP

This is a discussion on Debugging techniques in PHP within the PHP Programming forums, part of the Web Development category; Hi, Debugging techniques in PHP Setting up To learn the concepts described here, you are going to need PHP, a ...


Go Back   IT Community - Software Programming, Web Development and Technical Support > Web Development > PHP Programming

Register FAQ Members List Calendar Mark Forums Read
  #1 (permalink)  
Old 08-23-2007, 02:25 AM
sivaramakrishnan sivaramakrishnan is offline
D-Web Programmer
 
Join Date: Feb 2007
Posts: 74
sivaramakrishnan is on a distinguished road
Thumbs up Debugging techniques in PHP

Hi,
Debugging techniques in PHP

Setting up

To learn the concepts described here, you are going to need PHP, a Web server, and Eclipse. The latest version of PHP supported by the debugger extension is V5.0.3.

We need a Web server to parse the pages you create in PHP and display them to the browser. This article uses Apache V2. However, any Web server will suffice.

To take advantage of some of the debugging techniques here, you need to install Eclipse V3.1.1 and the plug-in: PHPeclipse V1.1.8. Since Eclipse requires Java™ technology, you also need to download that.

You also need the debugger module extension for PHP. Installing it is a bit tricky. Carefully follow the instructions for installing the debugger extension. For now, comment out the lines where you are asked to load and configure the extension in PHP in the php.ini file. We’ll uncomment those lines when we’re ready to use the debugger.

Error messages

Error messages are your first line of defense as a developer. You don't want to be developing code in PHP on a server that is not configured to display error messages. However, keep in mind that when your code is debugged and ready to go live, you want to make sure error reporting is turned off because you don't want visitors to your site seeing error messages that may give them enough knowledge to exploit a weakness and hack your site.

You can also use error messages to your advantage because they display the exact line of code that threw or generated an error. This makes debugging a matter of looking at the line number shown on the browser by the generated error and checking that line number in your code. Later, you will see that the PHPeclipse plug-in aides significantly in the development and debugging process by underlining syntax errors on the fly and by marking syntax errors with a red "x" when saving your file.

Let's take a look at how to turn error reporting on in the php.ini file and set the level of error reporting. Then you'll learn how to override these settings in the Apache configuration file.

Error reporting in PHP

There are many configuration settings in the php.ini file. You should already have set up up your php.ini file and placed it in the appropriate directory, as shown in the instructions in the Install PHP and Apache V2 on Linux document (see Resources). There are a couple configuration variables you should know about when debugging your PHP applications. Here they are with their default values:

display_errors = Off
error_reporting = E_ALL


You can discover the current default values of these variables by searching for them in the php.ini file. The purpose of the display_errors variable is self-evident -- it tells PHP whether or not to display errors. The default value is Off. To make your life easier in the development process, however, set this value to On by replacing Off:

display_errors = On


The error_reporting variable has a default value of E_ALL. This displays everything from bad coding practices to harmless notices to errors. E_ALL is a little too picky for my liking in the development process because it clutters the browser output by displaying notices on the screen for small things like uninitialized variables. I prefer to see the errors, any bad coding practices, but not the harmless notices. Therefore, replace the default value of error_reporting as follows:

error_reporting = E_ALL & ~E_NOTICE


Restart Apache, and you're all set. Next, you'll learn how to do the same thing on Apache.

Error reporting in the server

Depending on what Apache is doing, turning error reporting on in PHP may not work because you may have multiple PHP versions on your computer. It's sometimes hard to tell which PHP version Apache is pointing to because Apache can only look at one php.ini file. Not knowing which php.ini file Apache is using to configure itself is a security problem. However, there is a way to configure PHP variables in Apache to guarantee the setting of the correct error levels.

Also, it's good to know how to set these configuration variables on the server side to veto or pre-empt the php.ini file, providing a greater level of security.

You should already have toyed with basic configurations in the http.conf file at <apache2-install-dir>/conf/httpd.conf when you configured Apache.

To do the same as you just did in the php.ini file, add the following lines to your httpd.conf to override any and all php.ini files:

php_flag display_errors on
php_value error_reporting 2039



This overrides the flag you have set for display_errors in the php.ini file, as well as the value of error_reporting. The value 2039 stands for E_ALL & ~E_NOTICE. If you prefer E_ALL, set the value to 2047, instead. Again, make sure you restart Apache.

Next, we'll test error reporting on your server.

Testing error reporting

You will save a great deal of time if you leave error reporting enabled.

A simple PHP that generates an error

PHP Code:

<?php
print("The next line generates an error.<br>");
printaline("PLEASE?");
print(
"This will not be displayed due to the above error.");
?>
Regards,
sivaraman.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Sponsored Links
  #2 (permalink)  
Old 08-23-2007, 07:48 AM
vadivelanvaidyanathan vadivelanvaidyanathan is offline
D-Web Genius
 
Join Date: Feb 2007
Posts: 803
vadivelanvaidyanathan is on a distinguished road
Default Re: Debugging techniques in PHP

Debugging PHP code using DBG

Installing dbg (Windows)

[PHP install directory] is typically c:\php or c:\php5
[PHP ini path] is most commonly c:\windows

1. Download dbg from http://dd.cron.ru/dbg/downloads.php
2. From that zip, extract i386\php_dbg.dll.5.1.2 into [PHP install directory]\ext\
3. Rename [PHP install directory]\ext\php_dbg.dll.5.1.2 to [PHP install directory]\ext\php_dbg.dll
4. Edit [PHP ini path]\php.ini and add the following to the section labeled Windows extensions:

extension=php_dbg.dll

5. Verify that the following line is in php.ini, or add if necessary:

extension_dir = “[PHP install directory]\ext”

6. Add the following to the end of php.ini:

[debugger]
debugger.enabled = true
debugger.profiler_enabled = true
debugger.JIT_enabled = true
debugger.JIT_host = clienthost
debugger.JIT_port = 7869

7. Restart Apache. View info.php in the browser. It should contain a reference to dbg in the text near the Zend logo. It also should contain a dbg section in the configuration portion.

Installing dbg (Linux/FreeBSD)

Perform the following steps on the server.

[PHP extension directory] is typically /var/php/extensions

1. Download the correct version of dbg for your version of Linux/FreeBSD from http://dd.cron.ru/dbg/downloads.php
2. From that archive, extract i386/dbg.so-5.1.2 into [PHP extension directory]
3. Edit /etc/php.ini (on some installations this file may be in a different directory) and add the following:

extension=dbg.so-5.1.2

[debugger]
debugger.enabled=on
debugger.profiler_enabled=on
debugger.hosts_allow=host1 host2 host3
debugger.hosts_deny=ALL
debugger.ports=7869, 10000/16

The debugger.hosts_allow setting should contain the IP addresses of all of the client machines that will be allowed to debug the scripts.
4. Restart Apache. View info.php in the browser. It should contain a reference to dbg in the text near the Zend logo. It also should contain a dbg section in the configuration portion.

Now let’s move on to error messages as describe above thread.
__________________
V.Vadivelan

There never a wrong time to do the right thing.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 08-23-2007, 07:54 AM
vadivelanvaidyanathan vadivelanvaidyanathan is offline
D-Web Genius
 
Join Date: Feb 2007
Posts: 803
vadivelanvaidyanathan is on a distinguished road
Default Re: Debugging techniques in PHP

Testing error reporting

You will save a great deal of time if you leave error reporting enabled. Errors in PHP point you right to the error in your code. Create a simple PHP file, test.php, and define it as shown in Listing 1.

Listing 1. A simple PHP that generates an error

<?php print(”The next line generates an error.<br>”);
printaline(”PLEASE?”);
print(”This will not be displayed due to the above error.”);
?>

The first print() statement should display its contents to the Web browser. However, the second statement generates and displays an error to the Web page. This results in the last print() statement do nothing, as shown in Figure 1.

Figure 1. Generating an error



You have error reporting turned on! Next, we use print statements to help debug applications.

Introducing print statements

Because functional bugs in your application don’t generate errors, knowledge on how to accurately place and use print or die statements to debug your PHP application can be a great asset in your arsenal of debugging strategies. You can use print statements to narrow down the locations of problem statements in your code that may not be syntactically incorrect or bugs in the code, but they are bugs in the functionality of your code. These are the hardest bugs to find and debug because they throw no errors. You only know that what is being displayed to the browser isn’t what you intended, or that what you thought was being stored in your database isn’t being stored at all.

Suppose you are processing form data sent in via a GET request and want to display the information to the browser, but for whatever reason, the data is either not being submitted properly, or it isn’t being read from the GET request properly. To debug such a problem, it’s important to know what the value of the variable is, using a print() or a die() statement.

The die() statement halts program execution and displays text to the Web browser. The die() statement is particularly useful if you don’t want to have to comment out your code, and you only want everything up to the error and the error displayed and nothing after. Let’s test this concept of using print statements in PHP.

Debugging using print statements

In my years as a programmer where I developed applications on Linux® boxes with no handy GUI to tell me where my bugs were, I quickly caught on that the more print statements I laced my program with the more chances I had of narrowing down the bugs in my application to a single line. Create another PHP file, test2.php, and define it as shown in Listing 2.

Listing 2. Display all variables submitted via GET

<?php $j = “”;
print(”Lets retrieve all the variables submitted to this “);
print(”script via a GET request:<br>”);
foreach($_GET as $key => $i)
{
print(”$key=$j<br>”);
}
if($_GET[’Submit’] == “Send GET Request”)
$j = “done!<br>”;
?>
<form method=”GET”>
Name: <input name=”name”><br>
Email: <input name=”email” size=”25″><br>
<input name=”Submit” type=”submit” value=”Send GET Request”>
</form>

You may be able to spot the bug in Listing 2 very easily. Good for you! Note that this is a simple script, and is shown as an example in using print statements to debug. The script simply takes all variables in the GET request, if any, and displays them back to the browser. A form is also supplied for you to send variables to the server using a GET request for testing. See the output, as shown in Figure 2.

Figure 2. Output of test2.php



Now click the Send GET Request button. Notice that only the keys of the $_GET request got displayed to the browser, and the correct values did not. You can place a print statement within the loop to verify that data indeed exists at each element in the foreach loop. See Listing 3.

Listing 3. Using a print statement to verify code functionality

… foreach($_GET as $key => $i)
{
print(”Correct data? ” . $_GET[$key] . “<br>”);
print(”$key=$j<br>”);
}


The placed print statement is in bold font. Notice that you already know that the displayed $key values on the Web browser are correct, but for some reason, the values aren’t being displayed correctly. See the new output, as shown in Figure 3.

Figure 3. Output of modified test2.php



Now you know that your application is receiving the variables in the GET request correctly, so there must be a bug in your code. You look over and notice that the variable you are using for displaying the values, $j, is the wrong one. You specified $i in the foreach statement, which must have the correct values, but you accidentally typed in $j. You quickly fix the problem by replacing $j with $i and see the correct output by reloading the page, as shown in Figure 4.

Figure 4. Output of fixed test2.php



You can now remove or comment out the print statement you added because you have discovered the bug in your code. Notice that this is a small subset of the many errors you might experience while debugging your application. A good solution to a problem you may encounter when working with a database is to print out your SQL statements to make sure that what you are executing SQL you intended to execute.
__________________
V.Vadivelan

There never a wrong time to do the right thing.

Last edited by vadivelanvaidyanathan : 08-23-2007 at 07:56 AM.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 08-23-2007, 08:03 AM
vadivelanvaidyanathan vadivelanvaidyanathan is offline
D-Web Genius
 
Join Date: Feb 2007
Posts: 803
vadivelanvaidyanathan is on a distinguished road
Default Re: Debugging techniques in PHP

Use Firebug to Debug PHP Scripts

Ref link its explain with examples. Have a look at here
__________________
V.Vadivelan

There never a wrong time to do the right thing.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5 (permalink)  
Old 08-23-2007, 08:11 AM
vadivelanvaidyanathan vadivelanvaidyanathan is offline
D-Web Genius
 
Join Date: Feb 2007
Posts: 803
vadivelanvaidyanathan is on a distinguished road
Default Re: Debugging techniques in PHP

Use XDebug

Xdebug is an Open Source PHP extension for code debugging and profiling. Installation is straightforward and it will provide you with a wealth of information about your code, without being intrusive. One of the great features of Xdebug is, since it runs as an extension, there is no need to actually alter your code.

Install
Installation is simple, especially if you use on of the pre-compiled binaries provided on the site. Since i use XAMPP for for my development I grabbed the latest windows DLL and made the following change to my php.ini:

zend_extension_ts="C:ProgramFilesxamppphpextension sphp_xdebug-2.0.0rc3-5.2.1.dll"

Xdebug currently conflicts with the Zend optimizer and any other Zend extension (DBG, APC, APD etc)- although I've read about people having success, so combine at the your own risk.

You can confirm the installation went well by making a simple php_info() script. Full instructions and steps for rolling your own binary are available on the Xdebug install page.

Debugging
Without doing anything you'll see the benefits of Xdebug when messages are outputted to your browser.

Here's a simple script with a PHP warning. Xdebug generates a colorful back-trace showing the steps that generated the notice.

<?php
class main {
function main() {
$this->_init();
}

function _init() {
$array = 'string';

foreach($array as $item) {
echo $item;
}
}
}

$m = new main;
?>



Xdebug has a host of options to customize what, how, and where all the information it gathers is relayed to the developer. By enabling the Xdebug extension you also open up a set of Xdebug functions that can be used directly in your code. These are useful for quick debugging, but anything more you may end up bits of debug code spread throughout your site, which is exactly what you should using Xdebug to avoid in the first place.

The alternatives are to use Xdebug's remote debugging and profiling abilities.

Remote Debugging
Remote debugging requires a few more configuration changes, plus a client application that connects to your server for live debugging. The setup and use of the remote debugger goes a bit beyond the scope of this article. Needless to say it is an extremely powerful feature.

Profiling
Thanks to Xdebug's profiling ability you'll never have to write code like this again:

function getmicrotime() {
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}

$time_start = getmicrotime();
$m = new main;
$time_end = getmicrotime();

$time = $time_end - $time_start;

echo "Exec time: " . $time . "secondsn";

With the addition of a couple of lines to your htaccess, Xdebug will output detailed information about the processing of your script. The actual data can viewed using WinCacheGrind on Windows or KCacheGrind on Linux. The viewer provides an easy way to understand what goes into the execution of a script, as well as how long each part is taking.

Conclusion
The setup time and learning curve for the basic debug and profiling features of Xdebug are so low there really isn't any excuse to not be using them already. It only takes 15 minutes getting Xdebug configured and another 15 minutes getting to know it's features to make yourself a smarter, faster developer.
__________________
V.Vadivelan

There never a wrong time to do the right thing.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #6 (permalink)  
Old 08-28-2007, 08:33 AM
vivekanandan vivekanandan is offline
D-Web Trainee
 
Join Date: Jul 2007
Posts: 41
vivekanandan is on a distinguished road
Default Re: Debugging techniques in PHP

Hi,
In the object oriented programming, when we handling many object, for debug the specific object, just clone that object and just print it

$obj1 = clone $obj1;

print_r($obj1);


Regards,
vivekanandan
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Testing Techniques srikumar_l Software Testing 0 12-06-2007 01:09 AM
debugging an Asp.net web application simplesabita Software Testing 1 08-18-2007 12:55 AM
debugging ASP .NET vs PHP vivekanandan PHP Programming 1 08-11-2007 05:18 AM
Techniques in debugging prasath C and C++ Programming 0 07-17-2007 05:31 AM
8 magical SEO techniques! spid4r Search Engine Optimization 0 03-09-2007 12:04 AM


All times are GMT -7. The time now is 02:30 AM.


Copyright ©2004 - 2007, DiscussWeb. All Rights Reserved.

SEO by vBSEO 3.0.0