Guide to PHP and MySQL (University at Buffalo Version)
Chapter 12: Error Handling
PHP provides a number of functions that allow you to handle errors gracefully. You can even write your own custom error handling function or log errors to a file.
PHP Error Handling
The error_reporting()
function provides a way for you to set the error reporting level. Use the phpinfo()
function to find out the error reporting level for your server. See the Predefined Error Constants for an explanation. For example, to set the reporting level to all errors and warnings:
error_reporting(E_ALL | E_STRICT);
?>
PHP Error Logging
The ini_set()
function provides a way for you log your errors to a file.
ini_set("error_log","errors/my-errors.log");
error_reporting(0);
/*
Create the rest of your page here.
Errors will not be displayed.
Any fatal errors will still halt the execution, but they will still be logged.
*/
// set string with "functions" spelled wrong
$string_variable = "PHP has many built-in error handling functoins.";
// try to use str_replace to replace functions with features
// this will generate an E_WARNING
// because of wrong parameter count
str_replace();
// another way to call error_log():
error_log("str_replace(\"functions\",\"features\") failed");
?>
Using try / catch
to Handle Exceptions
The try / catch
statements provide a way for you to handle any errors gracefully.
$version = "1.0";
$element = "&";
try {
$dom = new DOMDocument($version);
$ab = new DOMElement($element);
$ab = $dom->appendChild($ab);
} catch (DOMException $e) {
print("<span style='color: #F00; font-weight: bold;'>Error:</span> $e");
}
try / catch
to Handle Exceptions Codetry / catch
to Handle Exceptions Output