Error handling is the process of changing the control flow of a program in response to error conditions. Error conditions can be caused by a variety of factors - programmer error, corrupt input data, software requirements deficiencies and in many other conditions.
A web application needs to be able to gracefully handle all of these potential problems - recovering from them where possible and exiting gracefully when the error is fatal.
We will show different error handling methods:
1. Simple "die()" statements
2. Custom errors and error triggers
3. Error reporting
Simple die() statement:
if(!file_exists("myfile.txt"))
{
die("File not found");
}
else
{
$file=fopen("myfile.txt","r");
}
?>
If the file does not exist you get an error message like this:
File not found
Custom errors and error triggers
You can create a custom error handler in PHP to replace the standard output to the browser. First you set up the error handler to replace the normal one, and set the ini values.
ini_set('display_errors', 'Off');
ini_set('log_errors', 'On');
define('ERROR_LOG_PATH', 'error_log.txt');
set_error_handler("custom_err_handler");
The custom function is defined we must then create it. The function takes 4 arguments.
1. $num: level of the error raised
2. $str: contains the error message
3. $file: filename that the error was raised in
4. $line: line number the error was raised at
function custom_err_handler($num, $str, $file, $line) {
print "Error Handler Called!";
$err = "";
$err .= "PHP Error\n";
$err .= "Number: [" . $num . "]\n";
$err .= "String: [" . $str . "]\n";
$err .= "File: [" . $file . "]\n";
$err .= "Line: [" . $line . "]\n\n";
error_log($err, 3, ERROR_LOG_PATH);
}
function Errfunction()
{
trigger_error("errror message");
}
Now call the Errfunction()
myFunction();