Processing of mistakes in PHP
Processing of mistakes with the help trigger_error () and set_error_handler ()
PHP gives a perfect opportunity to supervise arising mistakes. Here we shall talk how to process a mistake - to inform (or to not inform) about incident to the user, in case of need - to inform the manager with the help of email to write down the information on incident in a log-file.
So, for the beginning let's be defined{determined}, that such mistakes in PHP.
PHP supports the following levels of mistakes:
E_ERROR
E_WARNING
E_PARSE
E_NOTICE
E_CORE_ERROR
E_CORE_WARNING
E_COMPILE_ERROR
E_COMPILE_WARNING
E_USER_ERROR
E_USER_WARNING
E_USER_NOTICE
E_ALL
E_STRICT
Actually is simply constants which are used for definition of a level of processing of mistakes, constructions of a bat - mask. Constants have "speaking" names. Looking on a constant - we can say, that the mistake of level E_PARSE arises in case of a syntactic mistake, E_NOTICE is a reminder to the programmer about infringement of " good style " programming on PHP.
Some examples:
When connection with database MySQL (or) comes to the end with failure - interpreter PHP informs another on a mistake of level E_WARNING
Warning: mysql_connect (): Access denied for user: ' VVingless@localhost ' (Using password: YES)
In/home/mysite/index.php (line 83)
The remark: That interpreter PHP informed on mistakes - PHP should be adjusted in appropriate way: the flag display_errors should be switched on - 1, error_reporting directive should specify that it is necessary to display mistakes of level E_WARNING (it is desirable certainly and others). If values of these directives do not meet your requirements - you can try to establish them independently, having put in a folder with a script a file .htaccess (the point in the beginning of a name is obligatory) about such maintenances{contents}:
php_flag display_errors on
php_value error_reporting " E_ALL and ~E_NOTICE "
It means, that error messages will be shown, and all levels, except for E_NOTICE
When the programmer commits a syntactic mistake - interpreter PHP informs on a mistake of level E_PARSE
Parse error: parse error, unexpected ' (', expecting T_STRING in/home/mysite/index.php on line 150
But the levels of mistakes most interesting to us - E_USER_ERROR and E_USER_WARNING. As it becomes understandable from the name are levels of mistakes which the user can establish. For this purpose there is a function trigger_error () - with its{her} help, you can inform the user on incident how it does{makes} PHP.
As is known from a management{manual} on PHP - function trigger_error () accepts two parameters.
void trigger_error (string error_msg [, int error_type])
The first parameter - the text message on a mistake, for example " a file is not found ". The second parameter - defines{determines} a level of a mistake. Function trigger_error () works only with family of mistakes E_USER is means, that you can establish a mistake of level E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE and cannot establish a mistake of level E_WARNING. The second parameter is not obligatory, and by default accepts value E_USER_NOTICE.
Let's try:
We admit{allow}, our data for a news line are stored{kept} in a file news.txt and if the file is not found - it is necessary to inform about a mistake. The text of the program will look approximately so:
if (! file_exists('/home/mysite/news.txt ')) {
trigger_error (' News file not found ');
}
In result interpreter PHP informs about a mistake of level E_USER_NOTICE
Notice: News file not found in/home/mysite/index.php on line 47
But what it gives us? For the beginning that if in php.ini or a file .htaccess directives have been established
php_value log_errors "1"
php_value log_errors_max_len "1024"
php_value error_log "/home/mysite/my.log"
That in a file/home/mysite/my.log recording about incident will be automatically added.
[23-Mar-2004 13:52:03] PHP Notice: News file not found in/home/mysite/index.php on line 47
Further, with the help of function set_error_handler () we can establish own obrabotchik mistakes arising in execution time PHP of a script.
As is known from a manual - in PHP 4 function accepts the unique line parameter - a name of function which will be carried out each time when there is a mistake. PHP 5 enables to establish one more parameter - type of mistakes which will be processed with the help of ours obrabotchika. Function returns a line - a name of function obrabotchika which have been established till this moment.
string set_error_handler (callback error_handler [, int error_types])
We establish{install} so
set_error_handler ("my_error_handler");
The user function which will process mistakes, can accept the following entrance parameters:
- A code of a level of a mistake
- Line interpretation of a mistake
- A name of a file in which there was a mistake
- A line in which there was a mistake
It is necessary as to notice, that this function cannot process a mistake of levels E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING
It is connected with that, that mistakes of the listed levels occur before the interpreter receives the information about user obrabotchike mistakes.
So, we declare our function
function my_error_handler ($code, $msg, $file, $line) {
}
The remark: each more - less volumetric script is usually divided{shared} on some files for convenience of job with it . How to organize modul`nost` programs - a subject separately conversation. Now, I want only to advise to allocate the general{common} adjustments in a separate file which will be connected in the beginning of the program with the help of the instruction include, or with the help of auto_prepend_file directive. In this file it is possible will place also ours obrabotchik. Installation obrabotchika mistakes should will be carried out as it is possible closer to the beginning of the program, desirable right at the beginning.
That it will be convinced what is it really works - we shall create new PHP a file, and we shall try to start it
Contents of a file myerrortest.php
<? php
function my_error_handler ($code, $msg, $file, $line) {
echo " there Was a mistake $msg ($code) <br> n ";
echo " $file ($line) ";
}
set_error_handler (' my_error_handler ');
if (! file_exists('/home/mysite/news.txt ')) {
trigger_error (' News file not found ');
}
?>
The result of processing of the given file will be such:
There was mistake News file not found (1024)
/home/mysite/myerrortest.php (12)
Now we have function which obtains the data on all occuring mistakes. We shall think, as we can use it.
Let's process mistakes of levels
E_ERROR
E_WARNING
E_NOTICE
E_USER_ERROR
E_USER_NOTICE
First three mistakes in the good finished program should not occur in general, therefore we shall inform on them only to the user a conclusion of the text of a mistake to the screen. So it is possible to work, while a script in a status of development, then messages on them can either be disconnected, or to write down in a log-file.
As to other two - as you have already guessed - they I can be useful there. We shall cause mistakes of these levels in case of need. We admit{allow} - mistakes of level E_USER_ERROR - we shall cause in a case when the message on a mistake should get in a log-file and to be sent on e-mail to the manager (for example - a mistake at performance SQL of search, or absence parv access to a necessary file). Mistakes of level E_USER_NOTICE will be caused at occurrence of "easy" mistakes (for example - the user has incorrectly filled in the form, or has requested from base nonexistent recording).
Now our function of processing of mistakes will look approximately so:
// A few preliminary adjustments
// We establish{install} a mode of display of mistakes
// To display all mistakes, except for E_NOTICE
error_reporting (E_ALL and ~E_NOTICE);
// This constant is responsible
// Inclusion / deenergizing of a mode of debugging
// During debugging - messages are not sent
// By mail, and are simply printed on the screen
define (' DEBUG ', 0);
// It is a global variable, in which
// The message, which will be stored{kept}
// The user should see
$MSG = ";
// e-mail the developer where to send mistakes
define (' ADM_EMAIL ',' admin@example.com ');
// A log-file
define ('LOGFILE', '/home/mysite/mylog.log ');
// A difference in time with the server (in seconds)
define (' TIMEOFFSET ', 0);
// Function
function my_error_handler ($code, $msg, $file, $line)
{
// A global variable in which will be
// To enter the name the message on a mistake.
global $MSG;
// We pass{miss} mistakes of level E_NOTICE
// Also we ignore mistakes if the mode of an error message is switched - off
if (($code == E_NOTICE) or (error_reporting () == 0)) {
return;
}
// If we have called a mistake of level E_USER_NOTICE - simply
// To write down the text of a mistake in a global variable $MSG
// And to stop performance of function
if ($code == E_USER_NOTICE) {
$MSG = $msg;
Return;
}
// If a mistake of level E_ERROR - we print the text of a mistake
// Also we finish performance of a script
if ($code == E_ERROR) {
die (' <br> <b> ERROR: </b> '. $ msg. ' <br> In '. $ file. ' (line '. $ line. ') <br> ');
}
// If a mistake of level E_WARNING - we print the text of a mistake
// Also we stop performance of function
if ($code == E_WARNING) {
echo ' <br> <b> WARNING: </b> '. $ msg. ' <br> In '. $ file. ' (line '. $ line. ') <br> ';
Return;
}
// If a mistake of level E_USER_ERROR
if ($code == E_USER_ERROR) {
// We write down in a variable $MSG the text, about that that there was a mistake,
// The reason we shall not inform, only we inform that details
// Are sent on e-mail to whom follows.
$MSG = ' the Critical Mistake: action is executed nebylo. <br>
The message on a mistake has been sent to the developer. ';
// Details it is written down in a variable $text
$text = $msg. '<br>' .'Fajl: '. $ file. '('. $ line. ')';
// If constant DEBUG is established in 1 - we print the information about
// To a mistake on the screen if no - we send the text of a mistake mail
// Function error_mail () also we write in log - function error_writelog ()
if (DEBUG == 1) {
error_print ($text);
} else {
error_mail ($text);
error_writelog ($text);
}
Return;
}
}
// We establish{install} obrabotchik
set_error_handler (' my_error_handler ');
Now we describe service functions
// kh-n prints a mistake on the screen
function error_print ($text)
{
echo $text. ' <p> ';
}
// kh-n sends a mistake mail
function error_mail ($text)
{
$text = str_replace ("<br>", "n", $text);
$info = ' Time: '.get_datetime (). " nRemote IP: ".get_ip (). "n";
mail (ADM_EMAIL, " Error reporting ", $info. $ text);
}
// kh-n writes a mistake to a broad gully
function error_writelog ($text)
{
$text = str_replace ("<br>", "t", $text);
if ($fh = fopen (LOGFILE, " a + ")) {
fputs ($fh, get_datetime (). "t" .get_ip (). "t." $text. "n");
fclose ($fh);
}
}
// We receive time, in view of a difference in time
function get_time ()
{
return (date ("H:i", time () + TIMEOFFSET));
}
// We receive date, in view of a difference in time
function get_date ()
{
return (date ("Y-m-d", time () + TIMEOFFSET));
}
// We receive date and time, in view of a difference in time
function get_datetime ()
{
return get_date (). ' '.get_time ();
}
// We receive IP
function get_ip ()
{
return ($ _SERVER [' REMOTE_ADDR ']);
}
And at last an example of use
// kh-n writes down news in a file
function write_news ($title, $text)
{
$news_file = '/home/mysite/news.txt ';
// We check presence of heading - a mistake not critical
if (! trim ($title)) {
// To define{determine} that function has come to the end
// Failure - it is necessary to return false. Function
// trigger_error () - returns true, we shall be
// To return its{her} inverted result
return! trigger_error (' It is necessary to specify heading of news ');
}
// We check presence of the text of news - a mistake not critical
if (! trim ($text)) {
return! trigger_error (' It is necessary to specify the text of news ');
}
// We check presence of a file in which we shall write
// If the file is not found - there is a critical mistake
if (! file_exists ($news_file)) {
return! trigger_error (' the File of base of news is not found! ', E_USER_ERROR);
}
//.. Here preliminary data processing...
// We write down news
$fh = fopen ($news_file, " a + ");
fputs ($fh, $title. "t." $text. "n");
fclose ($fh);
// If all is normal - function returns true
return true;
}
// We try to write down news
// These data can come from the web-form
$res = write_news (" my news ", " the Text of my news ");
if ($res === false) {
// If has returned false - we print a mistake
echo $MSG;
} else {
// If that's all right - it is possible to inform about it
// And it is better otforvardit` than the user somewhere.
echo ' News has been added ';
}
That the example has earned - simply copy in a PHP-file three previous blocks of a code. Do not forget to establish access rights on a log-file 777 that a script could work, register with it correct ways and specify the e-mail. You can switch on a mode of debugging by installation of variable DEBUG in 1.
It is rather simple example, the subject can be developed.

|