PHP Tutorial Tutorials - PHP Error Handling

PHP Error Handling

When the PHP script run ,there may some errors occur.By default, the error message would be printed in the browser.
It's dangerous for the website security.The PHP script must hanlde these error gracefully.

Error Levels

Usually,The PHP engine will trigger an error event if there is a error occur at the runtime.
PHP predefine some constants to represent the error level integer value.
You can use the bitwise operators('|', '~', '!', '^' and '&') to combine these values or mask out certain types of errors.

Value Constant Description
1 E_ERROR Fatal run-time errors. These indicate errors that can not be recovered from. Execution of the script is halted.
2 E_WARNING Run-time warnings (non-fatal errors). Execution of the script is not halted.
4 E_PARSE Compile-time parse errors.
8 E_NOTICE Run-time notices. Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script.
16 E_CORE_ERROR Fatal errors that occur during PHP's initial startup.
32 E_CORE_WARNING Warnings (non-fatal errors) that occur during PHP's initial startup.
64 E_COMPILE_ERROR Fatal compile-time errors.
128 E_COMPILE_WARNING Compile-time warnings (non-fatal errors).
256 E_USER_ERROR User-generated error message.It is generatedby using trigger_error().
512 E_USER_WARNING User-generated warning message. It is generatedby using trigger_error().
1024 E_USER_NOTICE User-generated notice message.It is generatedby using trigger_error().
2048 E_STRICT Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code.
4096 E_RECOVERABLE_ERROR Catchable fatal error.
8192 E_DEPRECATED Run-time notices.
16384 E_USER_DEPRECATED User-generated warning message. It is generatedby using trigger_error().
32767 E_ALL All errors and warnings

Setting error level

There are 3 ways to set the error level:

  1. setting the configuration in the file PHP.ini
    set the configuration option error_reporting. it's default value is E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED.
    It means it will show all level errors except E_NOTICE, E_STRICT and E_DEPRECATED level errors.

In the Development environment,usually,we set E_ALL to show all level errors for debug.
In the Production environment, we set it to E_ALL & ~E_DEPRECATED & ~E_STRICT.

; error_reporting = E_ALL
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
  1. use error_reporting() function
    The error_reporting() function is used to set which PHP errors are reported in the current script page.
<?php
// Turn off all error reporting
error_reporting(0);
// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);
// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);
// Report all PHP errors
error_reporting(E_ALL);
// Report all PHP errors
error_reporting(-1);
?>
<?php
// Report all PHP errors
error_reporting(E_ALL);
// It will trigger an E_NOTICE error:  Notice: Undefined variable: a
var_dump($a); // NULL
?>
  1. using ini_set() function
    we can use ini_set() to set the value of a corresponding configuration option from php.ini
<?php
// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
?>

Use die() and exit() function

The die() is equivalent to exit().
They are used to simply display a custom message and terminate the current script.

Consider the following example which tries to open a text file.

<?php
    $file = fopen("filenotexist.txt", "r");
?>

If the file does not exist,a warning message will display:

Warning: fopen(filenotexist.txt): failed to open stream: No such file or directory

we can use file_exists() to prevent the user from getting such warning message.

<?php
$filename = "filenotexist.txt";
if(file_exists($filename)){
    $file = fopen($filename, "r");
} else{
    die("the file ".$filename." does not exist.");
    // or
    exit("the file ".$filename." does not exist.");
}
?>

// Or

<?php
error_reporting(E_ALL & ~E_WARNING & ~E_STRICT);
$filename = "filenotexist.txt";
$file = fopen($filename, "r") OR die("the file ".$filename." does not exist.");
?>

It also can exit with an error code, it's usually used in command mode:

//exit program normally
exit;
exit();
exit(0);

//exit with an error code
exit(1);
exit(2333);

Creating your user-defined Error Handler Function

By default, the error messages are display on the browser.
You can create an user-defined error handler function to log the error in file/database or sended by email.

yourErrorHanlderFunction($errLevel,$errStr,$errFile,$errLine,$errContext)
Parameter Description
errLevel error level
errStr error message
errFile the filename of the script file (Optional)
errLine the line where the error occurred(Optional)
errContext an array of every variable that existed in the scope at the point the error occurred.(Optional)
<?php
// error handler function
function myErrorHandler($errLevel, $errStr, $errFile, $errLine){
    echo "<b>Error level</b> [$errLevel]<br>\n";
    echo "<b>Error message</b> $errStr<br>\n";
    echo "<b>In file</b> $errFile<br>\n";
    echo "<b>On line</b> $errLine<br>\n";
}

Call the built-in set_error_handler() function to tell the PHP to use your error handler function.
Syntax:

set_error_handler ($error_handler [, $error_types] )
<?php
// error handler function
function myErrorHandler($errLevel, $errStr, $errFile, $errLine){
    echo "<b>Error level</b> [$errLevel]<br>\n";
    echo "<b>Error message</b> $errStr<br>\n";
    echo "<b>In file</b> $errFile<br>\n";
    echo "<b>On line</b> $errLine<br>\n";
}

// set to the user defined error handler
$old_error_handler = set_error_handler("myErrorHandler");

// trigger error
$a = 3/0;
?>

Outputs:

Error level [2]
Error message Division by zero
In file D:\Apache24\htdocs\index.php
On line 14

Error Logging - Log Error Messages in a File

We can also log the error messages into a file in the error handler function myErrorHandler().
Here we use error_log() to send an error message to a file.

<?php
// error handler function
function myErrorHandler($errLevel, $errStr, $errFile, $errLine){
    $logfile = "logs/err.log";
    $message = date("[Y-m-d H:i:s]");
    $message = $message."Error level [$errLevel]\n";
    $message = $message."Error message $errStr\n";
    $message = $message."In file $errFile\n";
    $message = $message."On line $errLine\n";

    error_log($message, 3, $logfile); // 3: the message is appended to the file
}
?>

Make sure the logs folder exists in your web root directory.

Error Logging - Send Error Messages by E-mail

error_log ( $message, $message_type, $destination)
if the $message_type = 1, the message is sent by email to the address in the $destination parameter.

<?php
// error handler function
function myErrorHandler($errLevel, $errStr, $errFile, $errLine){
    $logfile = "logs/err.log";
    $message = date("[Y-m-d H:i:s]");
    $message = $message."Error level [$errLevel]\n";
    $message = $message."Error message $errStr\n";
    $message = $message."In file $errFile\n";
    $message = $message."On line $errLine\n";

    error_log($message, 1, "admin@lautturi.org"); // 1:Send Error Messages by E-mail
}
?>

Trigger an Error

You can trigger an error manually.
The function trigger_error() is useful when you need to generate a user-level error/warning/notice message.

<?php
if ($divisor == 0) {
    trigger_error("Cannot divide by zero", E_USER_ERROR);
}
?> 
Date:2019-10-01 03:10:56 From:www.Lautturi.com author:Lautturi