CSCI 215 Web Programming II
Debugging & Error Handling
2
Error TypesParse (syntax) errors
◦Occur when the scripting engine fails to recognize code
◦Example: Incorrectly spelled or mistyped wordsRun-time errors
◦Occur when the engine encounters a problem while program is running
◦Example: Division by zeroLogic errors
◦Flaws in program design that prevent the program from running as intended
◦Example: Infinite loop
PHP Programming 3
Parse Error
11 <?php
12 for ($count = 10; $count >= 0; --$count)
13 if ($count == 0)
14 echo "<p>We have liftoff!</p>";
15 else
16 echo "<p>Liftoff in $count seconds.</p>";
17 }
18 ?>
PHP Programming 4
Parse Error
Run-Time ErrorsE_NOTICE Indicate that the script encountered something
that could indicate an error, but could also happen in the normal course of running a script.
E_USER_NOTICE User-generated notice message, generated by trigger_error().
E_WARNING Run-time warnings (non-fatal errors). Execution of the script is not halted.
E_USER_WARNING User-generated warning message, generated by trigger_error().
E_COMPILE_WARNING Fatal compile-time errors.
E_CORE_WARNING Warnings that occur during PHP's initial startup.
E_ERROR Fatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted.
E_USER_ERROR User-generated error message, generated by trigger_error().
E_COMPILE_ERROR Fatal compile-time errors.
E_CORE_ERROR Fatal errors that occur during PHP's initial startup.
E_PARSE Compile-time parse (syntax) errors.
notices
warnings
fatalerrors
PHP Programming 6
NoticesRaised for potential run-time
errors that do not prevent a script from executing
Examples◦use of an undefined variable◦defining a string without quotes
Notices<?php
error_reporting(E_ALL);
echo '<p>Error 1: Undefined variable:</p>';
echo $undefined_var;
echo '<p>Error 2: Unquoted string:</p>';
$some_var = tryetrhrtdf;
?>
http://ned.highline.edu/~tostrander/215/error_handling/error1.php
Notices
PHP Programming 9
WarningsDo not prevent a script from
executingIndicate that something clearly
wrong has happened and action should be taken.
Examples:◦File not found◦Database not available◦Missing function arguments
PHP Programming 10
Warningsfunction beginCountdown($time)
{
if (!isset($time))
$time = 10;
for ($count = $time; $count >= 0; —$count) {
if ($count == 0)
echo '<p>We have liftoff!</p>';
else
echo "<p>Liftoff in $count
seconds.</p>";
}
}
beginCountdown();
PHP Programming 11
Warnings
Warnings<?
echo '<p>Error 1: file not available:</p>';
$fp = fopen('file_does_not_exist.dat','r');
echo '<p>Error 2: db not available:</p>';
$results = mysql_query('SOME QUERY');
?>
http://ned.highline.edu/~tostrander/215/error_handling/error2.php
Warnings
PHP Programming 14
Fatal ErrorsRaised when a run-time error
prevents a script from executingSomething so terrible has
happened during execution of your script that processing cannot continue.
Examples:◦Parse error◦Calling an undefined function
Fatal Errors<?
error_reporting(E_ALL);
echo '<p>Error 1: Undefined function:</p>';
$fp = non_existing_function('an_arg');
echo 'Code never gets here!!!';
?>
http://ned.highline.edu/~tostrander/215/error_handling/error3.php
Raising ErrorsIt is possible to force a PHP error
at any point in your script.trigger_error($msg, $type);
Example:
if (!$name) {
trigger_error('No name entered', E_USER_ERROR);
}
…
PHP Programming 17
trigger_error()trigger_error() accepts two
arguments:◦A custom error message◦The error reporting level
E_USER_ERROR E_USER_WARNING E_USER_NOTICE
PHP Programming 18
if (isset($_GET['height']) &&
isset($_GET['weight'])) {
if (!is_numeric($_GET['weight'])
|| !is_numeric($_GET['height'])) {
trigger_error(“User did not enter numeric
values”, E_USER_ERROR);
}
} else {
trigger_error(“Values not entered”,
E_USER_ERROR);
}
$bodyMass = $_GET['weight'] / ($_GET['height']
* $_GET['height']) * 703;
print "Your body mass index is $bodyMass";
PHP Programming 19
PHP Programming 20
php.ini Directivesdisplay_errors
◦prints script error messages ◦default value of “On”
error_reporting ◦determines which types of error
messages PHP should generate◦by default, assigned a value of
“E_ALL”
Set Error Reporting Level
error_reporting($level)Used to control which errors are
displayed, and which are ignored. Only lasts for the duration of your
script
ini_set('display_errors', 1);
// turn all error reporting ON// error_reporting(E_ALL);
// Report all errors except E_NOTICE// error_reporting(E_ALL ^ E_NOTICE);
// Turn off all error reporting error_reporting(0);
// generate errorsecho '<p>Error 1: Use of an undefined variable.</p>';echo $undefined_var;echo '<p>Error 2: Use of an unquoted string.</p>';$some_var = tryetrhrtdf;echo '<p>Error 3: file not available:</p>';$fp = fopen('this_file_does_not_exist.dat','r');echo '<p>Error 4: db not available:</p>';$results = mysql_query('SOME QUERY');echo '<p>Error 5: call to undefined function:</p>';$fp = non_existing_function('an_arg');echo 'Code never gets here!!!';
http://ned.highline.edu/~tostrander/215/error_handling/error4.php
Hiding ErrorsHiding errors is NOT a
solution to a problem. It is useful, however, to
hide any errors produced on a live server.
While developing and debugging code, displaying all errors is highly recommended!
Suppressing ErrorsThe special @ operator can be
used to suppress function errorsAny error produced by the
function is suppressed regardless of the error reporting setting.
$db = @mysql_connect($h,$u,$p);if (!$db) {
trigger_error(‘blah’, E_USER_ERROR);}
Suppressing ErrorsError suppression is NOT a
solution to a problem.It can be useful to locally define
your own error handling mechanisms.
If you suppress errors, you must check for them yourself elsewhere.
Custom Error HandlingYou can write your own function to
handle PHP errors however you want.
The handler function should receive four arguments
The handler function should return true to indicate it has handled the error
Register the function in your script as the error handler
Custom Error Handlingfunction err_handler(
$errcode, $errmsg, $file, $lineno) {
echo ‘An error has occurred!<br />’;
echo “file: $file<br />”;
echo “line: $lineno<br />”;
echo “Problem: $errmsg”;
return true;
}
The handler must have 4 inputs..
1. error code2. error message3. file where error occurred4. line at which error
occurred
Custom Error HandlingThe function then needs to be registered
as your custom error handler:set_error_handler(‘err_handler’);
You can ‘mask’ the custom error handler so it only receives certain types of errors◦Example: register a custom handler just for
user triggered errors
set_error_handler(‘err_handler’,
E_USER_NOTICE | E_USER_WARNING |
E_USER_ERROR);
Custom Error HandlerA custom error handler is never
passed E_PARSE, E_CORE_ERROR or E_COMPILE_ERROR errors
These are considered too dangerous
function err_handler($errcode,$errmsg,$file,$lineno) {echo 'An error has occurred!<br />';
echo "file: $file<br />"; echo "line: $lineno<br />"; echo "Problem: $errmsg<br />";
return true;}
set_error_handler('err_handler'); // register handler
echo '<p>Error 1: Use of an undefined variable.</p>';echo $undefined_var;echo '<p>Error 2: Use of an unquoted string.</p>';$some_var = tryetrhrtdf;echo '<p>Error 3: file not available:</p>';$fp = fopen('this_file_does_not_exist.dat','r');echo '<p>Error 4: db not available:</p>';$results = mysql_query('SOME QUERY');echo '<p>Error 5: call to undefined function:</p>';$fp = non_existing_function('an_arg');echo 'Code never gets here!!!';
http://ned.highline.edu/~tostrander/215/error_handling/error5.php
PHP Programming 33
Other TipsTrace errorsFollow coding standardsWrite stub functions “Comment out” problematic linesAnalyze logic carefully
PHP Programming 34
Trace ErrorsTracing is the examination of
individual statements in an executing program
echo one of the most useful ways to trace PHP code
Use echo to display the contents of a variable, an array, or the value returned from a function
PHP Programming 35
function calculatePay() {
$PayRate = 15; $NumHours = 40;
$GrossPay = $PayRate * $NumHours;
echo “Gross Pay: $GrossPay<br />”;
$FederalTaxes = $GrossPay * .06794;
$StateTaxes = $GrossPay * .0476;
$SocialSecurity = $GrossPay * .062;
$Medicare = $GrossPay * .0145;
$NetPay = $GrossPay - $FederalTaxes;
echo “Net Pay 1: $NetPay<br />”;
$NetPay *= $StateTaxes;
echo “Net Pay 2: $NetPay<br />”;
$NetPay *= $SocialSecurity;
echo “Net Pay 3: $NetPay<br />”;
$NetPay *= $Medicare;
echo “Net Pay 4: $NetPay<br />”;
return number_format($NetPay, 2);
}
Stub Functions
function calcTax($amount)
{
return 1;
}
function isValid($email)
{
return true;
}Stubs return a hard-coded value
"Stubs" are empty functions that serve as placeholders for a program’s actual functions
PHP Programming 37
Use Comments to Debug$Amount = 100000;
$Percentage = .08;
printf(“The interest rate or a loan in the amount of
$%.2f is %s%%.<br />”, $Amount, $Percentage * 100);
$YearlyInterest = $Amount * $Percentage;
// printf(“The amount of interest for one year is
// $%.2f.<br />”, $YearlyInterest);
// $MonthlyInterest = $YearlyInterest / 12;
// printf(“The amount of interest for one month is
// $%.2f.<br />”, $MonthlyInterest);
// $DailyInterest = $YearlyInterest / 365;
// printf(“The amount of interest for one day is $
%.2f.
// <br />”, $DailyInterest);
The cause of an error in a statement is often the result of an error in a preceding statement
PHP Programming 38
Analyze LogicLogic errors are the hardest to
debugYou must analyze each statement
carefullyif (!isset($_GET['firstName'])) echo “You must enter your first name!”; exit();echo “Welcome to my Web site, ” . $_GET['firstName'];
PHP Programming 39
Analyze Logic
for ($count = 1; $count < 6; $count++);echo “$count<br />”;
$n = 1;while($n < 10){
echo $n;}
Isolate problematic
code
Learn Morehttp://www.w3schools.com/php/php_er
ror.asp
Top Related