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:

<?php
  error_reporting(E_ALL | E_STRICT);
?>

Figure 12-1: Setting the Error Reporting Level

PHP Error Logging

The ini_set() function provides a way for you log your errors to a file.

<?php
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");
?>

Figure 12-2: Writing Errors to a Log File
[01-Oct-2017 15:41:48 America/New_York] str_replace("functions","features") failed

Figure 12-3: Writing Errors to a Log File Output

Using try / catch to Handle Exceptions

The try / catch statements provide a way for you to handle any errors gracefully.

<?php
$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");
}

Figure 12-4: Using try / catch to Handle Exceptions Code
Error: exception 'DOMException' with message 'Invalid Character Error' in /home/content/16/12264716/html/phpguide/ch12.php:76 Stack trace: #0 /home/content/16/12264716/html/phpguide/ch12.php(76): DOMElement->__construct('&') #1 {main}

Figure 12-3: Using try / catch to Handle Exceptions Output
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Copyright © 2018 Jim Gerland