On this quick lesson, I’m going to provide a way for you to capture PHP errors and write custom logs.

 

PHP can already create error logs for you, but you cannot control the details of them. It may be handy to capture some additional details.

 

When a PHP script ends, you can run some checks to see if any errors have happened, then log it to file.

 

First, we need to tell PHP to call a function whenever a script execution has ended, this is done using “register_shutdown_function”.

 

<?php

register_shutdown_function('catchErrors');

// rest of your code

?>

 

This has told PHP to call a function named “catchErrors” at the end of the script run.

In order to add some custom information to the log, we will use a variable $custom_error_string to hold this. Because this variable is created and set outside of our error function, it needs to be declared as global inside the function (this will allows the function to have access to it).

<?php

register_shutdown_function('catchErrors');

$custom_error_string = "";

function catchErrors() {
 global $custom_error_string;

}

?>

 

We only want the function “catchErrors()” to do anything if an error has¬†occurred, so we need to check using the built-in function “error_get_last()”.

If any errors are found, write the log out to a file.

 

 

<?php

register_shutdown_function('catchErrors');

$custom_error_string = "";

function catchErrors() {
 global $custom_error_string;
 // location of the log file
 $error_log = "myerrors.log";
 // temp string to hold the error log
 $error_buffer = "";

 $e = error_get_last();
 if(isset($e['type']) {
  // an error has been found
  $error_buffer .= "Error recorded at: ".date("Y-m-d H:i:s")."\n";
  $error_buffer .= "Error type: {$e['type']}, ";
  $error_buffer .= "On Line: {$e['line']}, ";
  $error_buffer .= "Of File: $e['file'], ";
  $error_buffer .= "With message: $e['message']\n";

  // look for a custom error string to append to the log
  if($custom_error_string <> "") {
    $error_buffer .= "Custom error: $custom_error_string\n";
  }

  // write out to the log file
  $fp = fopen($error_log, 'w');
  fwrite($fp, $error_buffer);
  fclose($fp);
  // exist with non-zero exit code
  exit(9);
 }
 // clean exit
 exit(0); 

}

// you may want to create some custom message
$custom_error_string = "SQL Error 55 with $mysql_command\n";

?>

You may want to play around with what types of errors to handle – for example you may not be interested in E_WARNING (2) or E_NOTICE (8), but very interested in E_ERROR (1). Changing the IF statement to something like this may work for your needs:

 

// make sure error type is 1 (E_ERROR)
if(isset($e['type'] && $e['type'] == 1) {
 // rest of code in here
}

Tags: , ,