π PHP Debugging
Debugging is a necessary skill to develop when working with any computer coding. PHP offers some advice for finding those pesky bugs.
Common PHP Errors
Here are some things to look for when your script is not running as expected.
- Missing semicolons: omitting a semicolon at the end of a statement can cause all kinds of problems
- Mismatched parentheses, quotes and brackets. Make sure very opening quote, parenthesis and bracket has a corresponding closing element and vice versa!
- Double equal: In an if statement, make sure you use the == instead of =
- Variable names: check to make sure that you have used consistent variable names. Remember that php variables are case sensitive, so $myvar and $myVar are 2 different variables.
- Database connection failures.
Displaying Errors
If you are working on server that does not have display_errors = on, then you can turn it on for a single script.
ini_set('display_errors', 1);
If you need to set the error level to view all errors, you can use the following.
error_reporting(E_ALL | E_STRICT);
Displayed PHP Errors
Missing special characters like parenthesis, curly braces or semi-colons can cause your script to break and crash. Sometimes part of your page will display but often the entire page crashes with only a PHP error shown, if errors are turned on. Here are a few common PHP error messages.
- Missing semi-colon from the previous line of code.
- Parse error: syntax error, unexpected '$valid' (T_VARIABLE) in C:\xampp\htdocs\2learnweb\php\test-file.php on line 39
- Missing opening parenthesis.
- Parse error: syntax error, unexpected 'empty' (T_EMPTY), expecting '(' in C:\xampp\htdocs\2learnweb\php\test-file.php on line 37
- Missing closing parenthesis.
- Parse error: syntax error, unexpected '{' in C:\xampp\htdocs\2learnweb\php\test-file.php on line 37
- Missing curly brace on line 40 of the code produces an error on line 270, the last line of the code.
- Parse error: syntax error, unexpected end of file in C:\xampp\htdocs\2learnweb\php\test-file.php on line 270
- Undefined variable notice
- Notice: Undefined variable: firstname in C:\xampp\htdocs\2learnweb\php\test-file.php on line 153
- This means you have attempted to use a variable that has not been initialized. This notice indicates the line in the code that tried to use the variable. Variables need to be created and assigned values even of the value is empty or NULL before they are used in the code.
Database errors often show up as multiple errors. The root cause is usually one item but because database connections have multiple executions, you can often get multiple errors for one failure.
Warning: mysqli_connect(): (HY000/2002): No connection could be made because the target machine actively refused it. in C:\xampp\htdocs\2learnweb\php\test-file.php on line 16
Warning: mysqli_query() expects parameter 1 to be mysqli, bool given in C:\xampp\htdocs\2learnweb\php\test-file.php on line 20
Warning: mysqli_error() expects parameter 1 to be mysqli, bool given in C:\xampp\htdocs\2learnweb\php\test-file.php on line 23
Notice that each error contains clues to the root cause of the failure. Many times, the missing character or function is noted. Also a description of the failure is provided along with the file that cause it and even the line PHP failed on. Use these clues to scrutinize your code back from the failure. Pay attention to the corrections made for each error and soon you'll be debugging PHP as fast as you write the code.
Finding PHP Errors
Here are some techniques to help you find problems with your scripts. These techniques are especially helpful if your script isn't working as expected but not flagging any errors or warnings. Sometimes developers fail to include all name=value pairs or forget to name the form controls. There could be missing or erroneous data from the form submission. The methods below can help you see the information being sent between the client and the server in more detail.
- Use a PHP code editor with color coding, code hints and error detection such as VS Code or Notepad++.
- Turn on display_errors
- Use comments to comment out suspect code to eliminate it from processing. If the page loads normally, chances are that the problem is in the commented code.
- Use echo statements
echo "<p>\$var is $var</p>\n";
to display variable values or let you know if you reach a certain part of your codeecho "<p>Debug to line XX</p>\n";
such as a loop or function. Just add an echo to help you find out where your script is going awry. - Use
print_r($array);
to see the values in an array. This can be used with PHP Super Globals ($_REQUEST, $_POST, $_GET or $_SESSION) to see what is getting passed to the server as well. - Use
var_dump($varname);
to tell you the variable type and value. - Use
get_defined_vars();
to show all variables and values that PHP knows about. This includes system variables so you may get more than you bargained for. - Use
debug_backtrace();
to show all function calls up to the current point in the script. - The PHP manual has someΒ debugging advice with good suggestions from users.
- Use a debugger. There are several 3rd party debuggers you can use with PHP. If you are a Firefox user, you can download the extension FirePHP which allows you to debug in the browser.
Debugging $_POST Array Example
<?php
echo "<pre>";
print_r($_POST);
echo "</pre>";
?>
Output example from above code example.
The output of your code will be dependent on the makeup of your form and how you filled it out. The items in brackets [ ] below on the left are the names of the form fields. The text on the right are the values of the fields as entered by the user. The interests item is a checkbox item using an array to capture the multiple items selected.
From this, you can compare the submitted data to the expected form fields. It can help identify missing/misspelled fields or missing data. Often that is a result of typographical errors in the code.
Array ( [firstname] => Santa [lastname] => Claus [email] => sc@npole.com [username] => sclaus [password] => reindeer [pwconf] => reindeer [usertype] => instructor [interests] => Array ( [0] => css [1] => php [2] => mysql ) [county] => Dallas [zipcode] => 12345 [submit] => Add User )
Built-in Debug Script
You might also add a script to your site that allows you to turn on and off debugging where the script will print specific helpful output to the screen for you to verify the data interactions between the client and the server. If you include this script in the config.php file then include the config.php file in your template.php file, this will be available on-demand for every page of your site.
// Set up debug mode in the config file
function debug_data() { // call this function (below) to print arrays on any page.
echo '<pre>SESSION is ';
echo print_r($_SESSION);
echo 'COOKIE is ';
echo print_r($_COOKIE);
echo 'POST is ';
echo print_r($_POST);
echo 'GET is ';
echo print_r($_GET);
echo '</pre>';
}
//debug_data(); // Comment this out to hide debug information. Remove comment to display debug information.