Lost Password?

  #1 (permalink)  
Old 01-29-2008, 05:58 PM
Jordan's Avatar   
Jordan Jordan is offline
Administrator
 
Join Date: Nov 2005
Location: Hendersonville, NC
Age: 26
Posts: 5,978
Last Blog:
SAP, ERP and EDI
Rep Power: 20
Jordan has much to be proud ofJordan has much to be proud ofJordan has much to be proud ofJordan has much to be proud ofJordan has much to be proud ofJordan has much to be proud ofJordan has much to be proud ofJordan has much to be proud ofJordan has much to be proud of
Send a message via ICQ to Jordan Send a message via AIM to Jordan Send a message via MSN to Jordan
Default Debugging with PHP

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.
PHP Code:
ini_set("error_reporting"E_ALL); 
2) At the top of your script add this line

PHP Code:
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.

PHP Code:
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 Code:
<?php

print "Hello World;

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

Code:
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:
PHP Code:
?> 
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 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:

Code:
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 Code:
<?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.

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

Code:
Do Event
Now say the user enters "doevnet" instead of "doevent":
Code:
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:

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

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

Code:
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:

PHP Code:
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 Code:
<?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:

Code:
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 Code:
<?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.yourdomain.com/myscript.php?function=doevnet

An error will be seen:

PHP Code:
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.

Code:
@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 Code:
<?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.

Last edited by Jordan; 01-30-2008 at 10:48 AM.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

Sponsored Links
  #2 (permalink)  
Old 01-30-2008, 07:39 PM
John's Avatar   
John John is offline
Co-Administrator
 
Join Date: Jul 2006
Age: 19
Posts: 2,737
Last Blog:
Passwords
Rep Power: 20
John has much to be proud ofJohn has much to be proud ofJohn has much to be proud ofJohn has much to be proud ofJohn has much to be proud ofJohn has much to be proud ofJohn has much to be proud ofJohn has much to be proud ofJohn has much to be proud of
Send a message via AIM to John
Default

Very informative - Great work!
__________________
CodeCall Blog | CodeCall Wiki | Shareware | Linux Forum | My Blog
Chat with other CodeCall members on IRC; connect to irc.codecall.net and join #codecall
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
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

BB 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
PHP 4 end of life announcement Jordan Programming News 4 08-30-2007 09:55 AM
PHP Introduction clookid PHP Tutorials 10 01-16-2007 07:17 AM


All times are GMT -5. The time now is 08:17 PM.

Contest Stats

GoogleKeyw ........ 20.00000

Contest Rules

CodeCall Goal

Goal: 100,000 Posts
Complete: 67%

Ads