PHP - Error Handling and Reporting

advertisement
PHP - Error Handling and Reporting
Error output is very useful during development, but it is recommended errors be logged on the testing or
production server, not a public server. Error could be generated for various reasons, such as when the
script refers to a file which no longer exists in the location it is meant to be in.
Error and logging functions allow:



Error handling - catching errors raised by your program and then taking appropriate action.
Definitions for error handling rules, and modify the way the errors can be logged.
Output logs to email, a file or other locations.
Security
Sensitive information could potentially leak out of an application, such as database usernames and
passwords, if errors are allowed to be displayed publically. Allowing errors to be displayed and viewed
publically can also give clues to the structure of the website.
Error messages can be switched on or off depending on
requirements. For example, when a finally goes live, error
handling can be deactivated so PHP is not halted when the
code runs, nor sensitive error messages generated on the
screen.
php.ini
In some cases, error handling can be modified using the
php.ini settings file which is located on the Apache server
(installed with WAMP). This may be accessed on testing
server, depending on the user’s set up, e.g. navigating the
following address:
C:\wamp\bin\apache\Apache2.4.4\bin
… or by clicking on the green WAMP server icon (if you are using this) in the bottom right of the window.
If you have a website hosted by a company, access may be restricted - you may need to use other
strategies.
Here are some examples (below) from the php.ini file. The semicolon “;” at the beginning of a line makes
the line a comment (therefore has no effect). Removing the semicolon makes the line active. The
examples below shows error messages as displayed when an error occurs and error_reporting switched
to E_ALL (all errors and warnings)
error_reporting enabled or disabled
In the php.ini file the error_reporting setting can be changed from E_ALL to 0 to prevent the PHP scripts
reporting errors publically:
error_reporting = 0
If you cannot access the php.ini file on the server, you may change the settings dynamically using PHP
script directly on the web page, e.g. this example will change the error_reporting setting for the page:
<?php
ini_set(‘error_reporting’, 0)
?>
To turn error reporting off for a single document, include this line:
error_reporting(0);
Locating default error log files
Errors are written to log files (plain text) which over time can expand in size. Error logs can be found on
the WAMP testing server,
but are generally long
winded and not very user
friendly
die() function
This allows error messages to be displayed in
a more user friendly, more professional and
less random way, e.g. the following code
displays “File not Found” if welcome.txt is not
found.
<?php
if(!file_exists("welcome.txt"))
{
die("File not found");
}
else
{
$file=fopen("welcome.txt","r");
}
?>
If the code did not use the die() function, the error message would look similar to this:
Creating custom error logs
Web developers can write scripts to automatically handle errors and write the error information to a log
file, database, or automatically send by email to a developer team to deal with the problem.
In order to take more control of error logging, it is possible to generate custom log files for own use which
allow error information to be more easily managed. Error handling rules can be defined, to allow changes
and enhance error reporting.
The error reporting functions allow you to customize what level and kind of error feedback is given, ranging
from simple notices to customized functions returned during errors.
Error Report levels
Error reporting levels include a value (number) linked to content and description, here are some examples:
Value Constant (Integers)
1
Description
E_ERROR
Fatal run-time error that cannot be recovered from, such as a
memory allocation problem. Execution of the script is halted.
2
E_WARNING
Non-fatal run-time errors. Execution of the script is not halted
4
E_PARSE
Compile-time parse errors - should only be generated by the parser.
8
E_NOTICE
Run-time notices. The script found something that might be an error,
but could also happen when running a script normally
256
E_USER_ERROR
Fatal user-generated error. This is like an E_ERROR set by the
programmer using the PHP function trigger_error()
512
E_USER_WARNING
Non-fatal user-generated warning. This is like an E_WARNING set by
the programmer using the PHP function trigger_error(
1024
E_USER_NOTICE
User-generated notice. This is like an E_NOTICE set by the
programmer using the PHP function trigger_error()
4096
E_RECOVERABLE_ERROR Catchable fatal error. This is like an E_ERROR but can be caught by a
user defined handle (see also set_error_handler())
8191
E_ALL
All errors and warnings (E_STRICT became a part of E_ALL in PHP
5.4)
Source: w3schools.com and php.net – see
http://www.php.net/manual/en/errorfunc.constants.php for more info
Generate a simple error log file using the “Set Error Handler” function
Create a custom error handler which writes the error number and description of error to log file:
set_error_handler("customError");
Create a basic script to log the error code generated and write to a log file:
<?php
function customError($errno, $errstr)
{
$log = "error_log2.txt";
$handle = fopen($log, 'a+');
fwrite($handle, "Error Log \n");
fwrite($handle, date("l jS \of F Y h:i:s A")."\n");
fwrite($handle, "Error number: ".$errno." - ".$errstr."\n");
fwrite($handle,"\n -----------------------------------\n");
//Create a link to access the log file
echo '<p>Error log: <a href="error_log2.txt">Click here</a>';
die();
}
//set error handler
set_error_handler("customError");
//trigger errors (choose from below)
echo($test);
//$file=fopen("welcome.txt","r");
?>
The script above triggers an error which is then handled by the set_error_handler function which allows
the error to be displayed as a log file. A link to the log file is included. The log file is written on the server.
error_get_last() Function
This function returns the last error in an array containing 4 keys/values, or NULL if no errors have
occurred:




[type] - Error type
[message] - Error message
[file] - The file where the error occurred
[line] - The line where the error occurred
Example code to write last error to log file
<?php
echo $test; // create an error
$error_text = error_get_last();
print_r($error_text); //optional
$file = "error_log.txt";
$handle = fopen($file, 'a');
fwrite($handle, "Error Log \n");
fwrite($handle, date("l jS \of F Y h:i:s A")."\n");
fwrite($handle, $error_text["type"]."\n");
fwrite($handle, $error_text["message"]."\n");
fwrite($handle, $error_text["file"]."\n");
fwrite($handle, $error_text["line"]."\n");
fwrite($handle,"\n -----------------------------------\n");
echo '<p>Error log: <a href="error_log.txt">Click here</a>';
?>
PHP trigger_error() Function
The trigger_error() function creates a user-defined error message at a user-specified condition. It can be
used with the built-in error handler, or with a user defined function set by the set_error_handler()
function.
This function is useful when you need a user-defined message to a specified condition when running a
script runtime. This function returns FALSE if a non-valid error type is specified, and TRUE otherwise.
trigger_error(error_message,error_types)


error_message - required. Specifies the error message. Limited to 1024 characters in length
error_types - optional. Specifies the error type for this error message. Possible error types:
o E_USER_ERROR - fatal user-generated run-time error. Execution of the script is halted
o E_USER_WARNING - non-fatal user-generated run-time warning. Execution of the script is not
halted
o E_USER_NOTICE - default. User-generated run-time notice. The script found something that
might be an error, but could also happen when running a script normally
Example
<?php
$test=2;
if ($test>1)
{
trigger_error("A custom error has been triggered");
}
?>
Error_get_last()
The user_error() function is used to trigger an error message at a user-specified condition. It can be used
with the built-in error handler, or with a user defined function set by the set_error_handler() function.
This function returns FALSE if a non-valid error type is specified, and TRUE otherwise.
This function is an alias of the trigger_error() function.
user_error(error_message,error_types)
Download