Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

- - - - -

Debugging with PHP

runtime

  • Please log in to reply
1 reply to this topic

#1 Guest_Jordan_*

Guest_Jordan_*
  • Guest

Posted 29 January 2008 - 03:58 PM

Everyone makes errors and if you use PHP you will create bugs. The purpose of this tutorial is to give an introduction to debugging using PHP. You will learn basic ways to determine where problems occur as well as functions like var_dump().

First things First
When an error occurs you want the the error displayed right on the browser. While your production script may have errors turned off, for debugging purposes you should have this enabled. Follow these steps:

1) Edit your php.ini file. Set the directive display_errors to On. Restart your webserver.

Note: If you are on a shared host where you cannot edit your php.ini, and your display_errors directive is set to Off, to achieve the same effect you can use the ini_set() function to enable the directive at runtime.
ini_set("error_reporting", E_ALL);


2) At the top of your script add this line

error_reporting(E_ALL);
Without setting this you will only see the default value for error_reporting which is E_ALL & ~E_NOTICE & ~E_STRICT. This tells the interpreter to display All errors except Notices and Strict Notices. The values you can enter in error_reporting() are:

Value - Constant
1 -E_ERROR
2 -E_WARNING
4 -E_PARSE
8 -E_NOTICE
16 -E_CORE_ERROR
32 -E_CORE_WARNING
64 -E_COMPILE_ERROR
128 -E_COMPILE_WARNING
256 -E_USER_ERROR
512 -E_USER_WARNING
1024 -E_USER_NOTICE
6143 -E_ALL
2048 -E_STRICT
4096 -E_RECOVERABLE_ERROR

You can read more about these at PHP: error_reporting - Manual

Note: Turning All Errors Off
Even though it isn't mentioned in the PHP: error_reporting manual you can disable error reporting using the value 0.

error_reporting(0);
Starting with the Basics - Parse Errors
Parse errors can be one of the most irritating bugs for new PHP programmers to solve. A missing quote ("), bracket ({,}), and a multitude of other errors can be thrown by the interpreter which may leave you asking "What is wrong?".

Consider this code:


<?php

print "Hello World;

?>
You may notice the missing " after World and before ;. When this code is ran it casts the error:

Parse error: syntax error, unexpected $end in C:\wamp\www\broken.php on line 5
Which may leaving you asking, what is wrong with line 5?

Line 5:

?>
The line numbers may be a little deceiving at first causing a new PHP programmer to overlook the problem. The real issue is caused because the interpreter sees a quote before Hello and assumes a string will follow. With no ending quote the interpreter reaches the end of the script but never completes the string assignment.

When an error such as this is cast take a look at the actual line first, in this case ?>. If no immediate errors appear start working your way backwards line-by-line. Do a quick scan of each line making sure you have terminated them correct (;). Make sure matching pairs have an ending pair (in this case the quote).

Examples of matching pairs:
[ ]
{ }
" "
' '

Now consider the following code:


<?php
$yourName = "Jordan";

if $yourName == "Jordan")
{
echo "Hello $yourName";
}
?>
At a closer look you see that line 4 is missing the opening (. When this code is ran the interpreter will produce the following error:

Parse error: syntax error, unexpected T_VARIABLE, expecting '(' in C:\wamp\www\broken.php on line 4

Notice this error message correctly states the line number where the error occurred which is why it is very important to start on the line number given and work backwards. What actually happened was the interpreter read the "if" keyword and expected an open parenthesis followed by a condition. Instead it read "$yourName", a T_VARIABLE or token. What this message translates into is "While on line 4, I was expecting a '(' but received a variable."


Data Errors
Data errors are not displayed on your browser with a corresponding line number and there is no way see them. They can be some of the worst bugs that you deal with and may not be seen until months after your program release. They are also the hardest to debug.

Start Simple
An easy method of debugging is to print out your data.


<?php
$function = $_GET['function'];

if ($function == "doevent")
{
print "Do Event";
}
?>
In this script the user inputs a function via the URL which determines the output of the program.

http://www.yourdomain.com/myscript.php?function=doevent
Which should produce:

Do Event
Now say the user enters "doevnet" instead of "doevent":
http://www.yourdomain.com/myscript.php?function=doevnet
Which would produce nothing. How do you determine what the problem is? If the results are not what you expect there are some simple methods to determine what the problem is.

1) Print your Variable - In the same code above add print "Function - $function"; just under the $function assignment. This will allow you to see what is actually being passed through the GET value. In the error example above you would of seen an incorrect typing of "doevent" and been able to solve the problem.

2) Dump your variables - A more useful function is var_dump(). Adding var_dump($function); below the $function assignment will produce these results:

string(7) "doevnet"
This function is also very useful for arrays. This code (taken from php.net):


<?php
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
?>
Will produce a detailed view of the array:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  array(3) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
    [2]=>
    string(1) "c"
  }
}
3) A very similar function is the print_r() function which will produce almost the exact same results as above.

Use Checks
If the user enters nothing for the function the code displays nothing. This isn't very professional. To avoid this and find potential errors always use checks. A check makes sure that a value is filled correctly before executing statements. If function is a required field but the user left it blank an error message needs to be displayed. For this there are several methods:


if ($function == "") { print "Function Missing."; die(); }
if (empty($function) { print "Function Missing."; die(); }
if (assert($function != "") { print "Function Missing."; die(); }
There are several other methods in the PHP manual for error handling that may be used. Our completed script will look like this:


<?php
$function = $_GET['function'];
if (empty($function)
{
print "Function Missing.";
die();
}
elseif ($function == "doevent")
{
print "Do Event";
}
?>
Which, when the user enters a blank function, will produce:

Function Missing.
What if the user enters a function but it isn't specified in our if or case structures? Again, nothing will happen. A default method should be created for this type of problem. In the code above a "else" clause will create that.


<?php
$function = $_GET['function'];
if (empty($function)
{
print "Function Missing.";
die();
}
elseif ($function == "doevent")
{
print "Do Event";
}
else
{
print "Function does not exist!";
var_dump($function);
}
?>
When the user inputs:
http://www.yourdomai...unction=doevnet

An error will be seen:


Function does not exist!
string(7) "doevnet"
Allowing you to determine where the bug is, what it is and where it came from.


Tips and Tricks
1) Errors can be suppressed by using the @ operator. These are most often found on MySQL functions to prevent login/server information being displayed as a warning.

@mysql_connect();
2) The set_error_handler function allows you to control how your errors are displayed. For an example function visit the manual at PHP: set_error_handler - Manual

3) You can trigger your own errors with the trigger_error() function.

Taken from php.net

<?php
if (assert($divisor == 0)) {
trigger_error("Cannot divide by zero", E_USER_ERROR);
}
?>
4) You can change the display of your error/warning messages. Often it is hard to see them and you must resort to looking at the HTML source code. With a well defined display there will be no need however you must modify the PHP.INI or your .htaccess file.

Example: centricle : Tips for debugging PHP

5) Other userful functions
Conclusion

There are many more debugging methods and software that will even assist you in debugging. The methods mentioned here are basic concepts to help you solve bugs aimed at beginners.

I hope that this tutorial has helped you and if you have any questions or tips of your own post them here! If nothing else let us know that the tutorial was helpful.
  • 0

#2 John

John

    CC Mentor

  • Moderator
  • 4450 posts
  • Location:New York, NY

Posted 30 January 2008 - 05:39 PM

Very informative - Great work! :)
  • 0





Also tagged with one or more of these keywords: runtime

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download