set_error_handler

(PHP 4 >= 4.0.1, PHP 5)

set_error_handlerSets a user-defined error handler function

Description

mixed set_error_handler ( callback $error_handler [, int $error_types = E_ALL | E_STRICT ] )

Sets a user function (error_handler) to handle errors in a script.

This function can be used for defining your own way of handling errors during runtime, for example in applications in which you need to do cleanup of data/files when a critical error happens, or when you need to trigger an error under certain conditions (using trigger_error()).

It is important to remember that the standard PHP error handler is completely bypassed for the error types specified by error_types unless the callback function returns FALSE. error_reporting() settings will have no effect and your error handler will be called regardless - however you are still able to read the current value of error_reporting and act appropriately. Of particular note is that this value will be 0 if the statement that caused the error was prepended by the @ error-control operator.

Also note that it is your responsibility to die() if necessary. If the error-handler function returns, script execution will continue with the next statement after the one that caused an error.

The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.

If errors occur before the script is executed (e.g. on file uploads) the custom error handler cannot be called since it is not registered at that time.

Parameters

error_handler

The user function needs to accept two parameters: the error code, and a string describing the error. Then there are three optional parameters that may be supplied: the filename in which the error occurred, the line number in which the error occurred, and the context in which the error occurred (an array that points to the active symbol table at the point the error occurred). The function can be shown as:

handler ( int $errno , string $errstr [, string $errfile [, int $errline [, array $errcontext ]]] )
errno
The first parameter, errno, contains the level of the error raised, as an integer.
errstr
The second parameter, errstr, contains the error message, as a string.
errfile
The third parameter is optional, errfile, which contains the filename that the error was raised in, as a string.
errline
The fourth parameter is optional, errline, which contains the line number the error was raised at, as an integer.
errcontext
The fifth parameter is optional, errcontext, which is an array that points to the active symbol table at the point the error occurred. In other words, errcontext will contain an array of every variable that existed in the scope the error was triggered in. User error handler must not modify error context.

If the function returns FALSE then the normal error handler continues.

error_types

Can be used to mask the triggering of the error_handler function just like the error_reporting ini setting controls which errors are shown. Without this mask set the error_handler will be called for every error regardless to the setting of the error_reporting setting.

Return Values

Returns a string containing the previously defined error handler (if any). If the built-in error handler is used NULL is returned. NULL is also returned in case of an error such as an invalid callback. If the previous error handler was a class method, this function will return an indexed array with the class and the method name.

Changelog

Version Description
5.2.0 The error handler must return FALSE to populate $php_errormsg.
5.0.0 The error_types parameter was introduced.
4.3.0 Instead of a function name, an array containing an object reference and a method name can also be supplied as the error_handler.
4.0.2 Three optional parameters for the error_handler user function was introduced. These are the filename, the line number, and the context.

Examples

Example #1 Error handling with set_error_handler() and trigger_error()

The example below shows the handling of internal exceptions by triggering errors and handling them with a user defined function:

<?php
// error handler function
function myErrorHandler($errno$errstr$errfile$errline)
{
    if (!(
error_reporting() & $errno)) {
        
// This error code is not included in error_reporting
        
return;
    }

    switch (
$errno) {
    case 
E_USER_ERROR:
        echo 
"<b>My ERROR</b> [$errno$errstr<br />\n";
        echo 
"  Fatal error on line $errline in file $errfile";
        echo 
", PHP " PHP_VERSION " (" PHP_OS ")<br />\n";
        echo 
"Aborting...<br />\n";
        exit(
1);
        break;

    case 
E_USER_WARNING:
        echo 
"<b>My WARNING</b> [$errno$errstr<br />\n";
        break;

    case 
E_USER_NOTICE:
        echo 
"<b>My NOTICE</b> [$errno$errstr<br />\n";
        break;

    default:
        echo 
"Unknown error type: [$errno$errstr<br />\n";
        break;
    }

    
/* Don't execute PHP internal error handler */
    
return true;
}

// function to test the error handling
function scale_by_log($vect$scale)
{
    if (!
is_numeric($scale) || $scale <= 0) {
        
trigger_error("log(x) for x <= 0 is undefined, you used: scale = $scale"E_USER_ERROR);
    }

    if (!
is_array($vect)) {
        
trigger_error("Incorrect input vector, array of values expected"E_USER_WARNING);
        return 
null;
    }

    
$temp = array();
    foreach(
$vect as $pos => $value) {
        if (!
is_numeric($value)) {
            
trigger_error("Value at position $pos is not a number, using 0 (zero)"E_USER_NOTICE);
            
$value 0;
        }
        
$temp[$pos] = log($scale) * $value;
    }

    return 
$temp;
}

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

// trigger some errors, first define a mixed array with a non-numeric item
echo "vector a\n";
$a = array(23"foo"5.543.321.11);
print_r($a);

// now generate second array
echo "----\nvector b - a notice (b = log(PI) * a)\n";
/* Value at position $pos is not a number, using 0 (zero) */
$b scale_by_log($aM_PI);
print_r($b);

// this is trouble, we pass a string instead of an array
echo "----\nvector c - a warning\n";
/* Incorrect input vector, array of values expected */
$c scale_by_log("not array"2.3);
var_dump($c); // NULL

// this is a critical error, log of zero or negative number is undefined
echo "----\nvector d - fatal error\n";
/* log(x) for x <= 0 is undefined, you used: scale = $scale" */
$d scale_by_log($a, -2.5);
var_dump($d); // Never reached
?>

The above example will output something similar to:

vector a
Array
(
    [0] => 2
    [1] => 3
    [2] => foo
    [3] => 5.5
    [4] => 43.3
    [5] => 21.11
)
----
vector b - a notice (b = log(PI) * a)
<b>My NOTICE</b> [1024] Value at position 2 is not a number, using 0 (zero)<br />
Array
(
    [0] => 2.2894597716988
    [1] => 3.4341896575482
    [2] => 0
    [3] => 6.2960143721717
    [4] => 49.566804057279
    [5] => 24.165247890281
)
----
vector c - a warning
<b>My WARNING</b> [512] Incorrect input vector, array of values expected<br />
NULL
----
vector d - fatal error
<b>My ERROR</b> [256] log(x) for x <= 0 is undefined, you used: scale = -2.5<br />
  Fatal error on line 35 in file trigger_error.php, PHP 5.2.1 (FreeBSD)<br />
Aborting...<br />

See Also

add a note add a note

User Contributed Notes 69 notes

up
49
Philip
4 years ago
By this function alone you can not catch fatal errors, there is a simple work around. Below is part of my error.php file which handles errors and exceptions in the application. Before someone complains I'll add that I do not care that I am using globals, this file is part of my mini framework and without the 'config' variable the application would crash anyways.

<?php

/**
* Error handler, passes flow over the exception logger with new ErrorException.
*/
function log_error( $num, $str, $file, $line, $context = null )
{
   
log_exception( new ErrorException( $str, 0, $num, $file, $line ) );
}

/**
* Uncaught exception handler.
*/
function log_exception( Exception $e )
{
    global
$config;
   
    if (
$config["debug"] == true )
    {
        print
"<div style='text-align: center;'>";
        print
"<h2 style='color: rgb(190, 50, 50);'>Exception Occured:</h2>";
        print
"<table style='width: 800px; display: inline-block;'>";
        print
"<tr style='background-color:rgb(230,230,230);'><th style='width: 80px;'>Type</th><td>" . get_class( $e ) . "</td></tr>";
        print
"<tr style='background-color:rgb(240,240,240);'><th>Message</th><td>{$e->getMessage()}</td></tr>";
        print
"<tr style='background-color:rgb(230,230,230);'><th>File</th><td>{$e->getFile()}</td></tr>";
        print
"<tr style='background-color:rgb(240,240,240);'><th>Line</th><td>{$e->getLine()}</td></tr>";
        print
"</table></div>";
    }
    else
    {
       
$message = "Type: " . get_class( $e ) . "; Message: {$e->getMessage()}; File: {$e->getFile()}; Line: {$e->getLine()};";
       
file_put_contents( $config["app_dir"] . "/tmp/logs/exceptions.log", $message . PHP_EOL, FILE_APPEND );
       
header( "Location: {$config["error_page"]}" );
    }
   
    exit();
}

/**
* Checks for a fatal error, work around for set_error_handler not working on fatal errors.
*/
function check_for_fatal()
{
   
$error = error_get_last();
    if (
$error["type"] == E_ERROR )
       
log_error( $error["type"], $error["message"], $error["file"], $error["line"] );
}

register_shutdown_function( "check_for_fatal" );
set_error_handler( "log_error" );
set_exception_handler( "log_exception" );
ini_set( "display_errors", "off" );
error_reporting( E_ALL );
up
34
elad dot yosifon at gmail dot com
4 years ago
<?php
/**
* throw exceptions based on E_* error types
*/
set_error_handler(function ($err_severity, $err_msg, $err_file, $err_line, array $err_context)
{
   
// error was suppressed with the @-operator
   
if (0 === error_reporting()) { return false;}
    switch(
$err_severity)
    {
        case
E_ERROR:               throw new ErrorException            ($err_msg, 0, $err_severity, $err_file, $err_line);
        case
E_WARNING:             throw new WarningException          ($err_msg, 0, $err_severity, $err_file, $err_line);
        case
E_PARSE:               throw new ParseException            ($err_msg, 0, $err_severity, $err_file, $err_line);
        case
E_NOTICE:              throw new NoticeException           ($err_msg, 0, $err_severity, $err_file, $err_line);
        case
E_CORE_ERROR:          throw new CoreErrorException        ($err_msg, 0, $err_severity, $err_file, $err_line);
        case
E_CORE_WARNING:        throw new CoreWarningException      ($err_msg, 0, $err_severity, $err_file, $err_line);
        case
E_COMPILE_ERROR:       throw new CompileErrorException     ($err_msg, 0, $err_severity, $err_file, $err_line);
        case
E_COMPILE_WARNING:     throw new CoreWarningException      ($err_msg, 0, $err_severity, $err_file, $err_line);
        case
E_USER_ERROR:          throw new UserErrorException        ($err_msg, 0, $err_severity, $err_file, $err_line);
        case
E_USER_WARNING:        throw new UserWarningException      ($err_msg, 0, $err_severity, $err_file, $err_line);
        case
E_USER_NOTICE:         throw new UserNoticeException       ($err_msg, 0, $err_severity, $err_file, $err_line);
        case
E_STRICT:              throw new StrictException           ($err_msg, 0, $err_severity, $err_file, $err_line);
        case
E_RECOVERABLE_ERROR:   throw new RecoverableErrorException ($err_msg, 0, $err_severity, $err_file, $err_line);
        case
E_DEPRECATED:          throw new DeprecatedException       ($err_msg, 0, $err_severity, $err_file, $err_line);
        case
E_USER_DEPRECATED:     throw new UserDeprecatedException   ($err_msg, 0, $err_severity, $err_file, $err_line);
    }
});

class
WarningException              extends ErrorException {}
class
ParseException                extends ErrorException {}
class
NoticeException               extends ErrorException {}
class
CoreErrorException            extends ErrorException {}
class
CoreWarningException          extends ErrorException {}
class
CompileErrorException         extends ErrorException {}
class
CompileWarningException       extends ErrorException {}
class
UserErrorException            extends ErrorException {}
class
UserWarningException          extends ErrorException {}
class
UserNoticeException           extends ErrorException {}
class
StrictException               extends ErrorException {}
class
RecoverableErrorException     extends ErrorException {}
class
DeprecatedException           extends ErrorException {}
class
UserDeprecatedException       extends ErrorException {}
up
11
aditycse at gmail dot com
1 year ago
<?php
/**
* Used for logging all php notices,warings and etc in a file when error reporting
* is set and display_errors is off
* @uses used in prod env for logging all type of error of php code in a file for further debugging
* and code performance
* @author Aditya Mehrotra<aditycse@gmail.com>
*/
error_reporting(E_ALL);
ini_set("display_errors", "off");
define('ERROR_LOG_FILE', '/var/www/error.log');

/**
* Custom error handler
* @param integer $code
* @param string $description
* @param string $file
* @param interger $line
* @param mixed $context
* @return boolean
*/
function handleError($code, $description, $file = null, $line = null, $context = null) {
   
$displayErrors = ini_get("display_errors");
   
$displayErrors = strtolower($displayErrors);
    if (
error_reporting() === 0 || $displayErrors === "on") {
        return
false;
    }
    list(
$error, $log) = mapErrorCode($code);
   
$data = array(
       
'level' => $log,
       
'code' => $code,
       
'error' => $error,
       
'description' => $description,
       
'file' => $file,
       
'line' => $line,
       
'context' => $context,
       
'path' => $file,
       
'message' => $error . ' (' . $code . '): ' . $description . ' in [' . $file . ', line ' . $line . ']'
   
);
    return
fileLog($data);
}

/**
* This method is used to write data in file
* @param mixed $logData
* @param string $fileName
* @return boolean
*/
function fileLog($logData, $fileName = ERROR_LOG_FILE) {
   
$fh = fopen($fileName, 'a+');
    if (
is_array($logData)) {
       
$logData = print_r($logData, 1);
    }
   
$status = fwrite($fh, $logData);
   
fclose($fh);
    return (
$status) ? true : false;
}

/**
* Map an error code into an Error word, and log location.
*
* @param int $code Error code to map
* @return array Array of error word, and log location.
*/
function mapErrorCode($code) {
   
$error = $log = null;
    switch (
$code) {
        case
E_PARSE:
        case
E_ERROR:
        case
E_CORE_ERROR:
        case
E_COMPILE_ERROR:
        case
E_USER_ERROR:
           
$error = 'Fatal Error';
           
$log = LOG_ERR;
            break;
        case
E_WARNING:
        case
E_USER_WARNING:
        case
E_COMPILE_WARNING:
        case
E_RECOVERABLE_ERROR:
           
$error = 'Warning';
           
$log = LOG_WARNING;
            break;
        case
E_NOTICE:
        case
E_USER_NOTICE:
           
$error = 'Notice';
           
$log = LOG_NOTICE;
            break;
        case
E_STRICT:
           
$error = 'Strict';
           
$log = LOG_NOTICE;
            break;
        case
E_DEPRECATED:
        case
E_USER_DEPRECATED:
           
$error = 'Deprecated';
           
$log = LOG_NOTICE;
            break;
        default :
            break;
    }
    return array(
$error, $log);
}

//calling custom error handler
set_error_handler("handleError");

print_r($arra); //undefined variable
print_r($dssdfdfgg); //undefined variable
include_once 'file.php'; //No such file or directory
?>
up
9
kalle at meizo dot com
8 years ago
This may be of help to someone, who is/was looking for a way to get a backtrace of fatal errors such as maximum memory allocation issues, which can not be handled with user-defined functions, to pin-point the problem:

On a server hosting many sites that share common PHP includes, I set in one spot:

<?php
@ini_set ("error_log", "/my/path/php.err-" . $_SERVER ["HTTP_HOST"] . "-" . $_SERVER ["REMOTE_ADDR"] . "-" . $_SERVER ["REQUEST_METHOD"] . "-" . str_replace ("/", "|", $_SERVER ["REQUEST_URI"]));
?>

I actually used some additional information too from my software that I omitted, but that way, you'll find errors sorted more neatly in for example:-

/my/path/php.err-website.com-127.0.0.1-GET-path|index.html?xyz

And that at least helped me tremendously to then further pin-point where the problem is, as opposed to before just seeing the out of memory and not knowing which site/page it was on (as the PHP error only contains the very latest PHP code where it ran out of memory, which usually is just a shared included file, not the actual page).
up
3
webmaster at paramiliar dot com
9 years ago
We needed to use an error handler to handle SQL errors while passing the query along so the query is also logged and this is what we came up with, its kind of an ugly bridge but it works 100%

<?php

function myErrorHandler($errno, $errstr, $errfile, $errline){
    switch (
$errno) {
    case
E_USER_ERROR:
        if (
$errstr == "(SQL)"){
           
// handling an sql error
           
echo "<b>SQL Error</b> [$errno] " . SQLMESSAGE . "<br />\n";
            echo
"Query : " . SQLQUERY . "<br />\n";
            echo
"On line " . SQLERRORLINE . " in file " . SQLERRORFILE . " ";
            echo
", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
            echo
"Aborting...<br />\n";
        } else {
            echo
"<b>My ERROR</b> [$errno] $errstr<br />\n";
            echo
"  Fatal error on line $errline in file $errfile";
            echo
", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
            echo
"Aborting...<br />\n";
        }
        exit(
1);
        break;

    case
E_USER_WARNING:
    case
E_USER_NOTICE:
    }
   
/* Don't execute PHP internal error handler */
   
return true;
}

// function to test the error handling

function sqlerrorhandler($ERROR, $QUERY, $PHPFILE, $LINE){
   
define("SQLQUERY", $QUERY);
   
define("SQLMESSAGE", $ERROR);
   
define("SQLERRORLINE", $LINE);
   
define("SQLERRORFILE", $PHPFILE);
   
trigger_error("(SQL)", E_USER_ERROR);
}

set_error_handler("myErrorHandler");

// trigger an sql error
$query = "SELECT * FROM tbl LIMIT 1";
$sql = @mysql_query($query)
    or
sqlerrorhandler("(".mysql_errno().") ".mysql_error(), $query, $_SERVER['PHP_SELF'], __LINE__);
   

?>
up
5
dannykopping at gmail dot com
3 years ago
Keep in mind that, when attempting to set a statically-defined error handler on a namespaced class in PHP >= 5.3, you need to use the class namespace:

<?php
set_error_handler
('\\My\\Namespace\\Bob::errorHandler');
?>
up
2
francois vespa
6 years ago
This is a note when using php from the terminal (the CLI interface). From the command line, even if you have some kind of error user handler function so STDERR will not display, fatal errors will still cause the PHP interpreter to display error text. There is nothing you can do about that php-wise. If using UNIX/Linux, you can add " 2>/dev/null" at the end of your command to force STDERR not to show
up
5
silkensedai at online dot fr
10 years ago
i made an error handler that print also the backtrace and that can die on some errors. It can be useful if you want to die on every error you find.

<?php

function my_error_handler($errno, $errstr, $errfile, $errline){
   
$errno = $errno & error_reporting();
    if(
$errno == 0) return;
    if(!
defined('E_STRICT'))            define('E_STRICT', 2048);
    if(!
defined('E_RECOVERABLE_ERROR')) define('E_RECOVERABLE_ERROR', 4096);
    print
"<pre>\n<b>";
    switch(
$errno){
        case
E_ERROR:               print "Error";                  break;
        case
E_WARNING:             print "Warning";                break;
        case
E_PARSE:               print "Parse Error";            break;
        case
E_NOTICE:              print "Notice";                 break;
        case
E_CORE_ERROR:          print "Core Error";             break;
        case
E_CORE_WARNING:        print "Core Warning";           break;
        case
E_COMPILE_ERROR:       print "Compile Error";          break;
        case
E_COMPILE_WARNING:     print "Compile Warning";        break;
        case
E_USER_ERROR:          print "User Error";             break;
        case
E_USER_WARNING:        print "User Warning";           break;
        case
E_USER_NOTICE:         print "User Notice";            break;
        case
E_STRICT:              print "Strict Notice";          break;
        case
E_RECOVERABLE_ERROR:   print "Recoverable Error";      break;
        default:                    print
"Unknown error ($errno)"; break;
    }
    print
":</b> <i>$errstr</i> in <b>$errfile</b> on line <b>$errline</b>\n";
    if(
function_exists('debug_backtrace')){
       
//print "backtrace:\n";
       
$backtrace = debug_backtrace();
       
array_shift($backtrace);
        foreach(
$backtrace as $i=>$l){
            print
"[$i] in function <b>{$l['class']}{$l['type']}{$l['function']}</b>";
            if(
$l['file']) print " in <b>{$l['file']}</b>";
            if(
$l['line']) print " on line <b>{$l['line']}</b>";
            print
"\n";
        }
    }
    print
"\n</pre>";
    if(isset(
$GLOBALS['error_fatal'])){
        if(
$GLOBALS['error_fatal'] & $errno) die('fatal');
    }
}

function
error_fatal($mask = NULL){
    if(!
is_null($mask)){
       
$GLOBALS['error_fatal'] = $mask;
    }elseif(!isset(
$GLOBALS['die_on'])){
       
$GLOBALS['error_fatal'] = 0;
    }
    return
$GLOBALS['error_fatal'];
}

?>

Usage :

<?php
error_reporting
(E_ALL);      // will report all errors
set_error_handler('my_error_handler');
error_fatal(E_ALL^E_NOTICE); // will die on any error except E_NOTICE
?>
up
2
eregon at eregon dot info
12 years ago
It is not possible to handle fatal errors with own handler. Even if you have set your own handler, fatal error will be always handled by PHP's default handler. The reason is the script may be in unstable state after fatal error occurence (details here: http://marc.theaimsgroup.com/?l=php-dev&m=97673386418430&w=2).
up
2
Steffen Staehle
12 years ago
Two notes on using set_error_handler() on behaviour that I noticed when migrating an application from php 4.2.1 to php 4.3.9 (I do not yet have php 5.0 available, this might not apply there!).

1. setting the system error handler

If you want to set the standard php error handler again, after having set your own error handler, this works in php 4.2.1 by passing in an empty string:

<?php

  
function my_handler($log_level, $log_text, $error_file, $error_line)
   {
     
// if an error occurs here, the standard error
      // would be called (to avoid recursion)

      // do something useful
      // ...
  
}

  
$last_handler = set_error_handler("my_handler");

  
// after this, $last_handler == ""

   // restore standard error handler

  
$last_handler = set_error_handler("");

  
// after this, $last_handler == "my_handler"

?>

The very same code now raises an error in php 4.3.9:

   set_error_handler() expects argument 1, '', to be a valid callback

(Since the return value of the first call to set_error_handler() is still the empty string "", I don't see how this can be done any more. I don't really need this, because I use my own handlers as shown below, but it might be good to be aware of this.)

2. setting your own 'second level' handler

If you have set your own error handler, and want to replace it by another one (other than the standard php error handler) while it is being executed, note that the return value of set_error_handler when used INSIDE the error handler is "" instead of the name of the previous handler! This is not too surprising, because during execution of your self defined error handler, php replaces it with the standard php error handler to avoid infinite loops in case of problems inside the handler. This is only interesting if you want nested handlers as I do. Background of my design:

   1st level handler: log into DB
   2nd level handler: log into flat file (if log into DB fails)
   3rd level handler: print to stdout (if log into flat file fails) (this is the sytem handler, finally).

<?php

  
function my_fallback_handler($log_level, $log_text, $error_file, $error_line)
   {
     
// if an error occurs here, the standard error
      // would be called (to avoid recursion)

      // do something useful
      // ...

  
} // my_fallback_handler

  
function my_handler($log_level, $log_text, $error_file, $error_line)
   {
     
// if an error occurs here, the standard error
      // would be called (to avoid recursion)

      // but we want to have a fallback handler different
      // to the standard error handler

     
$last_handler = set_error_handler("my_fallback_handler");

     
// I expected $last_handler == "my_handler"
      // (which it would outside my_handler())
      // but here it is the empty string ""

      // do something useful
      // ...

      // now set the 1st level handler again:
      // (do NOT use $last_handler as argument,
      // because it equals "")

     
$last_handler = set_error_handler("my_handler");

   }
// my_handler

  
$last_handler = set_error_handler("my_handler");

?>
up
2
sijmen at digitized dot nl
13 years ago
@jayp at groovejob dot com
As I said before, the reference operator doesn't have any effect on the the error handler.

Proof of concepts:
http://trouby.digitized.nl/set_error_handler2.php
http://trouby.digitized.nl/set_error_handler2.php?source=1
up
2
Anonymous
13 years ago
It seems that when you're letting PHP know that you have a custom  error handler, you're not able to -update/set new- variables inside the class. Example:

<?php
class error {
   var
$error;

   function
error() {
      
$this->setIni();    // this causes PHP to ignore all other changes to the class.
  
}

   function
handler() {
       echo
$this->error.'!!';
   }

   function
setText($text) {
        
$this->error = $text;
   }

   function
setIni() {
      
set_error_handler(array($this, 'handler'));
   }
}

$eh = new error;
$eh->setText('Error! <br>');  // this will not be saved

trigger_error('text', E_USER_ERROR);
// prints '!!'
?>

How it should be done:
<?php
class error {
   var
$error;

   function
error() {
        
// dont let PHP know of our error handler yet
  
}

   function
handler() {
       echo
$this->error.'!!';
   }

   function
setText($text) {
        
$this->error = $text;
   }

   function
setIni() {
      
set_error_handler(array($this, 'handler'));
   }
}

$eh = new error;
$eh->setText('Error! <br>');  // this WILL work
$eh->setIni();  // call this method when you're ready with configuring the class. All other methods that will be called will have no effect on the errorHandling by PHP

trigger_error('text', E_USER_ERROR);
// prints 'Error! <br>!!'
?>
up
5
wfinn at riverbed dot com
9 years ago
"The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called."

This is not exactly true.  set_error_handler() can't handle them, but ob_start() can handle at least E_ERROR.

<?php

function error_handler($output)
{
   
$error = error_get_last();
   
$output = "";
    foreach (
$error as $info => $string)
       
$output .= "{$info}: {$string}\n";
    return
$output;
}

ob_start('error_handler');

will_this_undefined_function_raise_an_error();

?>
up
3
Jacob Slomp
4 years ago
This might be handy if you don't want your clients to see the errors, and you do want to be one step ahead of them.

It emails you the errors even if it's a parse error.

set_error_handler() doesn't work for what I wanted.

<?php
ini_set
('log_errors',TRUE);
ini_set('error_log','tiny_uploads/errors.txt');

if(
$_SERVER['REMOTE_ADDR'] != "YOUR IP ADDRESS"){
   
ini_set('display_errors',false);
}
  
function
byebye(){

       
$dir = dirname(__FILE__);
        if(
file_exists($dir."/tiny_uploads/errors.txt")){
       
           
$errors = file_get_contents($dir."/tiny_uploads/errors.txt");
           
            if(
trim($errors)){
           
               
$head = "From: php_errors@".str_replace('www.','',$_SERVER['HTTP_HOST'])."\r\n";
               
               
$errors .= "---------------------------------------------\n\n";
               
               
$errors .= "\n\nServer Info:\n\n".print_r($_SERVER, 1)."\n\n";
               
$errors .= "---------------------------------------------\n\n";
               
               
$errors .= "\n\nCOOKIE:\n\n".print_r($_COOKIE, 1)."\n\n";
               
$errors .= "---------------------------------------------\n\n";
               
               
$errors .= "\n\nPOST:\n\n".print_r($_POST, 1)."\n\n";
               
$errors .= "---------------------------------------------\n\n";
               
               
$errors .= "\n\nGET:\n\n".print_r($_GET, 1)."\n\n";
               
               
               
mail("YOUR@EMAIL.COM","PHP Error ".$_SERVER['HTTP_HOST']."", $errors , $head);
               
               
$fp = fopen($dir."/tiny_uploads/errors.txt","w+");
               
fputs($fp, "");
               
fclose($fp);   
            }   
        }
}
register_shutdown_function("byebye");
?>
up
1
roy
15 years ago
Useful thing to note - if your error handler throws an error in itself, PHP is smart enough to use the deault error handler to handle it. This way, you don't end up in infinite flaming loops of death. This seems to be true, at least, in PHP 4.2.

('Course, there are ways to create your handler to handle even this situation, but it's probably best left this way for general purposes.)
up
2
nicolas dot grekas+php at gmail dot com
4 years ago
If you want to be sure that the native PHP error handler is called without resetting the handler stack (as set_error_handler(null) does), you can simply call set_error_handler with $error_types set to zero. This can be especially use full in conjunction with e.g. error_get_last():

<?php

// var_dump or anything else, as this will never be called because of the 0
set_error_handler('var_dump', 0);
@
$undef_var;
restore_error_handler();

// error_get_last() is now in a well known state:
// Undefined variable: undef_var

... // Do something

$e = error_get_last();

...

?>
up
2
periklis
7 years ago
How to handle fatal errors in php 5.2:

<?php
register_shutdown_function
('shutdownFunction');
function
shutDownFunction() {
   
$error = error_get_last();
    if (
$error['type'] == 1) {
       
//do your stuff    
   
}
}
?>
up
2
stepheneliotdewey at GmailDotCom
10 years ago
The manual states:

"errcontext will contain an array of every variable that existed in the scope the error was triggered in. User error handler must not modify error context."

But do you know WHY you must not modify the error context? It appears that errcontext is (in effect if not literally) created by taking $GLOBALS and adding the non-global local variables as additional entries in that array, then passing the whole thing *by reference*.

(You can prove this to be true if you set up a custom error handler and then print_r($errcontext) within it, because $GLOBALS will be printed as a recursive array).

In other words, the language in the manual is misleading, because errcontext is NOT a copy of the variables that existed when the error WAS triggered, but rather is a reference to the *existing LIVE variables* in the calling script.

This includes superglobal variables like $_SERVER, $_POST, $_GET, etc., as well as all user-defined variables in scope.

The significance of that is that if you modify errcontext, you will be modifying those other variables, not just for the life of your error handling function, but for the life of the calling script as well.

That doesn't matter if you plan to halt execution in your error handling function, but it will lead to unexpected behavior if you modify $errcontext and then return to the program's normal flow after handling the error, because the variables will stay modified. For example, if you unset $_SERVER in your custom error handling function, it will remain unset once the function is over and you have returned to the page that generated the error.

This should be made clearer in the manual, starting by marking errhandler with an ampersand (&) for passage by reference in the "Parameters" section above, like so:

handler ( int $errno, string $errstr [, string $errfile [, int $errline [, array &$errcontext]]] )
up
5
phpmanual at NO_SPHAMnetebb dot com
14 years ago
Given this code:

class CallbackClass {
    function CallbackFunction() {
        // refers to $this
    }

    function StaticFunction() {
        // doesn't refer to $this
    }
}

function NonClassFunction() {
}

there appear to be 3 ways to set a callback function in PHP (using set_error_handler() as an example):

1: set_error_handler('NonClassFunction');

2: set_error_handler(array('CallbackClass', 'StaticFunction'));

3: $o =& new CallbackClass();
   set_error_handler(array($o, 'CallbackFunction'));

The following may also prove useful:

class CallbackClass {
    function CallbackClass() {
        set_error_handler(array(&$this, 'CallbackFunction')); // the & is important
    }
   
    function CallbackFunction() {
        // refers to $this
    }
}

The documentation is not clear in outlining these three examples.
up
1
nizamgok at gmail dot com
8 years ago
I have realized that a few people here mentioned that you cannot capture parse errors (type 4, E_PARSE). This is not true. Here is how I do. I hope this helps someone.

1) Create a "auto_prepend.php" file in the web root and add this:

<?php
register_shutdown_function
('error_alert');

function
error_alert()
{
        if(
is_null($e = error_get_last()) === false)
        {
               
mail('your.email@example.com', 'Error from auto_prepend', print_r($e, true));
        }
}
?>

2) Then add this "php_value auto_prepend_file /www/auto_prepend.php" to your .htaccess file in the web root.

* make sure you change the email address and the path to the file.
up
2
dorphalsig at NOSPAMgmail dot com
6 years ago
This actually works to catch Fatal errors...

<?php
function shutdown()
{
   
$a=error_get_last();
    if(
$a==null)  
        echo
"No errors";
    else
        
print_r($a);
   
}
register_shutdown_function('shutdown');
ini_set('max_execution_time',1 );
sleep(3);
?>

it will output
Array ( [type] => 1 [message] => Maximum execution time of 1 second exceeded [file] => /path/to/file_name.php [line] => 136 )
up
1
gotrunko at hotmail dot com
10 years ago
To ereg error in a text file

<?php
$log_file
="log.txt";

set_error_handler(log_handler);

function
log_handler ( $errno, $errstr$errfile, $errline, $errcontext )
{
   
$context = var_export($errcontext, TRUE);
   
log_error_ereg("errno:$errno ($errstr) file:$errfile, line:$errline, context:$context\n");
}

function
log_error_ereg($mess)
{
    global
$log_file;

   
$fd = fopen($log_file, 'a');
    if(!
$fd)
    {
        echo
"<pre>$mess</pre>";
    }
    else
    {
        if(!
fwrite($fd, date('Y-m-d H:i:s')." ERR : \n$mess\n\n"))
        {
            echo
"<pre>$mess</pre>";
        }
       
fclose($fd);
    }
}
?>
up
1
mmtache at yahoo dot com
14 years ago
The @ operator sets the error_reporting() value to 0.
This means you can use it with your own Error Handler too. for example:

function userErrorHandler($errno, $errmsg, $filename, $linenum, $vars) {
   if (error_reporting())
echo $errmsg;
    }
set_error_handler("userErrorHandler");

function test(){
trigger_error("Error Message", E_USER_WARNING);
}

@test(); // doesn't output anything
up
1
phil at propcom dot co dot uk
4 years ago
It is important to note that the registered SPL autoloader will NOT be called if an E_STRICT error triggers the error handler which, in turn, tries to use classes which are not yet loaded.

In this instance, you should manually load classes required by the error handler.
up
1
jtrick77 at gmail dot com
4 years ago
For anyone interested in the actual translated error codes and their meanings:

1    E_ERROR (integer)     Fatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted.    
2    E_WARNING (integer)     Run-time warnings (non-fatal errors). Execution of the script is not halted.    
4    E_PARSE (integer)     Compile-time parse errors. Parse errors should only be generated by the parser.    
8    E_NOTICE (integer)     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 (integer)     Fatal errors that occur during PHP's initial startup. This is like an E_ERROR, except it is generated by the core of PHP.    
32    E_CORE_WARNING (integer)     Warnings (non-fatal errors) that occur during PHP's initial startup. This is like an E_WARNING, except it is generated by the core of PHP.    
64    E_COMPILE_ERROR (integer)     Fatal compile-time errors. This is like an E_ERROR, except it is generated by the Zend Scripting Engine.    
128    E_COMPILE_WARNING (integer)     Compile-time warnings (non-fatal errors). This is like an E_WARNING, except it is generated by the Zend Scripting Engine.    
256    E_USER_ERROR (integer)     User-generated error message. This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error().    
512    E_USER_WARNING (integer)     User-generated warning message. This is like an E_WARNING, except it is generated in PHP code by using the PHP function trigger_error().    
1024    E_USER_NOTICE (integer)     User-generated notice message. This is like an E_NOTICE, except it is generated in PHP code by using the PHP function trigger_error().    
2048    E_STRICT (integer)     Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code.    Since PHP 5 but not included in E_ALL until PHP 5.4.0
4096    E_RECOVERABLE_ERROR (integer)     Catchable fatal error. It indicates that a probably dangerous error occurred, but did not leave the Engine in an unstable state. If the error is not caught by a user defined handle (see also set_error_handler()), the application aborts as it was an E_ERROR.    Since PHP 5.2.0
8192    E_DEPRECATED (integer)     Run-time notices. Enable this to receive warnings about code that will not work in future versions.    Since PHP 5.3.0
16384    E_USER_DEPRECATED (integer)     User-generated warning message. This is like an E_DEPRECATED, except it is generated in PHP code by using the PHP function trigger_error().    Since PHP 5.3.0
32767    E_ALL (integer)     All errors and warnings, as supported, except of level E_STRICT prior to PHP 5.4.0.     32767 in PHP 5.4.x, 30719 in PHP 5.3.x, 6143 in PHP 5.2.x, 2047 previously

(Copied from http://php.net/manual/en/errorfunc.constants.php)
up
1
Klauss
3 months ago
Hi everyone. I don't know if it is an old behavior of previous versions, but currently you can set exception and error handlers as private or protected methos, if, only if, you call `set_exception_handler()` or `set_error_handler()` within a context that can access the method.

Example:
    <?PHP
        $Handler
= new class ()
        {
            public function
__construct ()
            {
               
set_error_handler([&$this, 'HandleError']);
               
set_exception_handler([&$this, 'HandleException']);
            }
            protected function
HandleError ( $Code, $Message, $File = null, $Line = 0, $Context = [] )
            {
               
// Handle error here.
           
}
            private function
HandleException ( $Exception )
            {
               
// Handle exception here.
           
}
        }
   
?>

NOTE: these methods must match the callbacks parameters signatures.
up
0
chris at ocproducts dot com
1 year ago
Note that error handlers don't run recursively. If you have an error while an error handler is running (in the error handler itself or code called from it) then you won't get the error handler called again.

This has subtle ramifications for $php_errormsg. If you are relying on your error handler to suppress certain kinds of error message from going into $php_errormsg (via return true; because error_reporting doesn't affect $php_errormsg setting) then this will not work for any code called within that error handler.
up
0
Fi Ras
2 years ago
up
0
felix dot b at outlook dot com
2 years ago
I saw many checking for all the error constants manually in a switch statement. If you just want to add the type of the error (E_WARNING, E_NOTICE, etc) to your ErrorException, use array_search() with get_defined_constants():

new ErrorException("[" . array_search($errno, get_defined_constants(), true)  . "] " . $errstr, 0, $errno, $errfile, $errline);
up
0
yvan.burrie
2 years ago
Here's a way to customize error messages for each function or functions within classes:

<?php

// This lists all error messages from each function including functions contained within classes and their associated scope:
$_ERRORS [ 'errorTest::makeError1' ]= 'Attempting to make an error' ;
$_ERRORS [ 'errorTest->makeError2' ]= 'Attempting to make another error' ;
$_ERRORS [ 'strpos' ]                = 'Failed to find offset of data from string' ;
$_ERRORS [ 'strlen' ]                = 'Failed to calculate length of string' ;
$_ERRORS [ 'substr' ]                = 'Failed to retrieve data from string' ;
$_ERRORS [ 'pack' ]                    = 'Failed to export binary package' ;
$_ERRORS [ 'unpack' ]                = 'Failed to import binary package' ;
$_ERRORS [ 'number_format' ]        = 'Failed to represent numeracy as number' ;
$_ERRORS [ 'implode' ]                = 'Failed to implode array elements' ;
$_ERRORS [ 'explode' ]                = 'Failed to explode array elements' ;
$_ERRORS [ 'fopen' ]                = 'Failed to initialize stream opening' ;
$_ERRORS [ 'fread' ]                = 'Failed to extract data from stream' ;
$_ERRORS [ 'fwrite' ]                = 'Failed to retract data into stream' ;
$_ERRORS [ 'fseek' ]                = 'Failed to seek offset from stream' ;
$_ERRORS [ 'rewind' ]                = 'Failed to rewind offset from stream' ;
$_ERRORS [ 'ftell' ]                = 'Failed to retrieve offset from stream' ;
$_ERRORS [ 'file_get_contents' ]    = 'Failed to retrieve contents from file' ;
$_ERRORS [ 'file_put_contents' ]    = 'Failed to conduct contents into file' ;
$_ERRORS [ 'stream_get_contents' ]    = 'Failed to retrieve contents from stream' ;
$_ERRORS [ 'call_user_func_array' ]    = 'Failed to call function with array' ;
$_ERRORS [ 'max' ]                    = 'Failed to retrieve maximum elements' ;
$_ERRORS [ 'min' ]                    = 'Failed to retrieve minimum elements' ;
$_ERRORS [ 'array_chunk' ]            = 'Failed to retrieve chunks of array elements' ;
$_ERRORS [ 'array_combine' ]        = 'Failed to combine keys for array elements' ;
$_ERRORS [ 'array_diff' ]            =
$_ERRORS [ 'array_diff_assoc' ]        =
$_ERRORS [ 'array_diff_key' ]        =
$_ERRORS [ 'array_diff_uassoc' ]    =
$_ERRORS [ 'array_diff_ukey' ]        = 'Failed to differentiate array elements' ;
$_ERRORS [ 'array_fill' ]            =
$_ERRORS [ 'array_fill_keys' ]        = 'Failed to allocate array elements' ;
$_ERRORS [ 'array_flip' ]            = 'Failed to flip array elements to keys' ;
//$_ERRORS [ 'array_slice' ]            = 'Failed to slice array elements' ;

/**

*/
set_error_handler
(
    function (
$code , $text , $file , $line , array $cont ) use ( $_ERRORS )
    {
        if (
error_reporting () )
        {
           
$result = [] ;
            foreach (
debug_backtrace () as $detail )
            {
               
$string = @ $_ERRORS [ @ $detail [ 'class' ] . @ $detail [ 'type' ] . @ $detail [ 'function' ] ] ;
                if ( isset (
$string ) )
                {
                   
$result [] = $string ;
                }
            }
            if (
count ( $result ) )
            {
               
$result = implode ( ': ' , array_reverse ( $result ) ) . '.' ;
            }
            else
            {
               
$result = 'Undefined procedural behaviour' ;
            }
            throw new
ErrorException ( $result , $code , 0 , $file , $line ) ;
        }
    } ,
   
E_ALL | E_STRICT
) ;

// Examples :

class errorTest
{
    static function
makeError1 ()
    {
       
strpos () ;
    }

    public function
makeError2 ()
    {
       
strlen () ;
    }
}

$err = new errorTest ;

try
{
   
substr () ;
}
catch (
Exception $E )
{
    echo
$E -> getMessage () . "\n" ;
}

try
{
   
errorTest :: makeError1 () ;
}
catch (
Exception $E )
{
    echo
$E -> getMessage () . "\n" ;
}

try
{
   
$err -> makeError2 () ;
}
catch (
Exception $E )
{
    echo
$E -> getMessage () . "\n" ;
}

try
{
   
// this function was not listed in the $_ERRORS variable and will therefore view the default message
   
array_slice () ;
}
catch (
Exception $E )
{
    echo
$E -> getMessage () . "\n" ;
}

/*
The above examples will output:

    Failed to retrieve data from string.
    Attempting to make an error: Failed to find offset of data from string.
    Attempting to make another error: Failed to calculate length of string.
    Undefined procedural behaviour
*/
?>
up
-1
chris at ocproducts dot com
1 year ago
Note that $php_errormsg (with track_errors) is only set if the function returns false (i.e. bubble on). If you return true then $php_errormsg will not be set.
up
0
contact [a] ionisis [.] com
7 years ago
There seems to be no way to access to access the _POST, _GET, etc if you call trigger_error from within a function inside a class file.
up
0
devermin at ti0n dot net
7 years ago
At work I have some code with errors that uncatched are the causes of integrity loss (people calling web services with file_get_contents that fails silently and afterwards insert garbage in the database).

here is the solution I found to transform a specific set of errors into exception and afterwards be able to selectively act (with the error code) regarding categories : 

<?php
ini_set
('error_reporting',E_ALL^E_NOTICE);

## first 10 bits reserved for the initial error number
define('EMASK',(~0)<<10);
define('ECODEMASK',~EMASK);
## categories
define('IOERROR', 1<<10);
define('EMPTYPARMS', 1<<11);
define('FAILURE', 1<<12);
## string error patterns => code

$catch_me=array(
   
"/^(file_get_contents)\((.*)\).*failed to open stream: (.*)/ " =>
        array (
'mesg' => "IO::Failed to open stream with",
               
'code' => IOERROR | FAILURE
       
),
   
"/^fopen\(.*\): Filename cannot be empty/" =>
        array(
'msg' => "Parameters::empty",
               
'code' => EMPTYPARMS
       
)
    );
function
error_2_exception($errno, $errstr, $errfile, $errline,$context) {
    global
$catch_me;
    foreach (
$catch_me as $regexp  => $res) {
        if(
pled7 default">$catch_me as 2te-norrline
,$errstr,$catch_me <))rd">) {
            throw new ($res">$res,$res">$res(   $line ;
  &
  &nord">;
  &nord">;
  &
;
  &
; }rd">);
just wacmust marors)e

();
just wabsp;k exisAttemw
($res);
set_error_handler(error_2_exc:empty");
"

($res); try {gories
> Atnp; raisto makinto exce\o/

(); }acmustword">(Excepstch_me) {
Excebynt">## cyord">;
  &
( ?>$CodeF>$line () . "\n" :: ; }rd">);

?>
up
0
$dducts dot com
7 years ago
ere's a wtrap fat initialontentslasandler ,e="50%E the $,lename co to rdts dplet is the so, b/ci will bu to rom gs disds bdelyid areli sttce 4.3.5 .s file.
up
0
7 years ago
on). I"geoseFailede() funsucde with , __de aguct()alonena sAt to call fu, bl wilena'tn truef you rturns ptioork Id for built error halog (with the.utput:
on). If you rturns thus lisowttempe iitial seems logged,ere iscriptrormsghalt, exit() sAy$errptio__de aguct()'s> >a'tnhappen.utput:
t There se i ) is the so errnsucde waas />hero a)alog c) totede with , al b)sdlt'tnrd">E_USER the $s file.
up
0
7 years ago
<?php
  &nng">'error_repeption
(E_ALL() ;
  &ord">(
(, 10Codemak  ) {
      &nboreach (
'(filspaini_setmak">$res">$res((((mak  ) {
                  &bsp;kword">;
            }
        }

      &nboreach (
maklt">10mak">$res">$res;
    }

  &oach (
($resr />
tml"> Notemarormples ) isamust runtim iitials. Sopeople caa metho lista non exisAttemfuntwray_doeion wa call tere ishutoted error hs file.
up
0
7 years ago
Notet">// this funm's f you rNULLerrnshave as n, even wtrue willatchenoiitials./r /> Fal insts="e,et">//>here iaas /wtruetc if you ">// this funerved fot">## tim :set if the function reNULLesaulty bee thee willaiion prel besnitial error-h sp; Unds file.
up
0
7 years ago
E_ormplesbareoplndec) totedeay to n.set error-h f the fu.asses:


E_  UndeRRORS vatbr />
nbsp; &//efinedsne keta fuffbr />
$errno$res[] = $resE_&nheelf ubsp; Undeconsts=s bak, baz"r />}

E_  UndeRRORS vatbr />
nbsp; &>[] =
r />
Asetc if n Thearbageiioporveebove e, bads=nwrittontscripts de


$errno">$res[] = $res|
nbsp; &>[] =
?>
up
0
7 years ago
Excs;ealso feature">erdebug_backinclu regapossi va&
funarguay el.asses:

<?phpt;?php$cf$string ">$res[] = 1$>">$res[] = $res($errno, $errstr">$res, $errfile">$res, $errline">$res)
{
  &>[] =
;
  &
'error_repeption10() ;
    }

    global

  &>[] =
Excrd">;
  &
()
       
      &s noword">($errno, $errstr, $errfile, $errline[] =
       
[] = array_randler(debug_bacdefineExcrd">;
       
(10  [] = ?>$Codesubstr [] = ?>getM>$Code$file [] = ?>        $line [] = ?>define[] = ?>() ;
    }

   
) {
            nbsp;  
=> 'IOERROR') {
            nbsp;  
=> ) {
            nbsp;  
=> 'IOERROR') {
            nbsp;  
E_nbsp;       nbsp;   => E_OERROR') {
            nbsp;  
=> 'IOERROR') {
            nbsp;  
=> ) {
            nbsp;  
=> 'IOERROR') {
            nbsp;  
=> ) {
            nbsp;  
=> 'IOERROR') {
            nbsp;  
=> ) {
            nbsp;  
E_nbsp;     => E_OERROR') {
            nbsp;  
=> E_OERROR') {
            nbsp;  
=> 'IOE>) {
            nbsp;  
    las_exisAodefine($errno,       &>[] = [] = $errno() ;
  &n   {
      &>[] =
[] = $res:: $errstr, $errfile$line $errline    as
      &nbor if (reach (
$res[] = $res">$res">$resfu>">$res">$res">$restak  ">$res">$resas               &
   
[] = takrrline(                    tak  ">$res">$resfu>">$res[] = $resfu>">$res">$res">$restak  ">$res">$resas               &
   
[] = takrrline(                    tak  ">$res">$res;
  &
">$res[] = 1">$res(r />
          &T_bac:n>">$res
(">$res;
  &
($errno(E_$errno(E_$errno() ;
          &bsp;kword">;">() ;
      &lass="dobsp; {
          &nbreach (
">$res[] = 10$dro adminbsp; {
               
$>">$res$andler($>">$res,$res"\n" ">$res[] = ) {
                           
mak&Hrror_h>">$res                getM>$Code">$res;">() ;
    }
()br />
getM>$Code)
{
    echo
$res()
{
  & in a sword">(
((      &aas /ord">(">$res( ">$res">$res[] = ($res(
      &aas /ord">(
$res($res($res($res($res">$resas =>                 [] = $res(>">$res(
               
">$res">$res($res($res($res($res          &ction ord">(([] = () ;
    }nbsp; }
>[] =
?>
up
0
7 years ago
>span>&l ">() ;
&tch_me
$errno$errnor />
tosbarinclu ed, c) wont get anycitialfault m, but c) toscriptrmplescrash aineout anycoutput (Theape ibug-lasabas /ervefurke andetails:div> http://bugse-no.net/buge-note.p41862&par).each (
7 years ago
funlf already sp; Und object whlt">maintainrega>cedsnero ayou "e objects curry e lasa .asses:============================bsp; }
ctirigger_error-h("/a>mak"woutput:
$ObjectNass clast"output:
$last-ult"new
fun/a>mak(ault">, ault">$, aultult", ault">$ewnbsp; {nbsp; g$ObjectNassoutput:
eval("nbsp; g\$".$ObjectNass.";"woutput:eval("\$object=\$".$ObjectNass.";"woutput:
$object-ult">&lEtialHrror_hwault">, ault">$, aultult", ault">$ew;
$object=nullwbsp; }}bach (
$an Ras
7 years ago
; I'veogotrmocheconveni="c entlsaflcitial o eErrorExceconverter:utput:
/a>() ;
&public staticenbr />funitialHrror_hCayodebu($ode", alass=", ault", ault", aconlass)  {
  &$e = new() ;
  &$e-ult"ult">= ault"d">() ;
  &$e-ult"ult">= ault"d">() ;
  &throw $eoutput:
  }n
ctirigger_error-h(nbsp; "Cy to EErrorExc", "itialHrror_hCayodebu"), E_ALL);bach (
up
0
7 years ago
ctirigger_error-h("c) tHrror_h"woutput:
// Pg>7e,Complt", Coch, etce t ">maksbsp; }ini_f (r'lassriggers',fals")d">() ;ini_f (r'igger_prepend_sass=">,'aulthassult"aultheadult"aultMETA http-equiv="horresh" conlant="0;URL=/iggere-notmsg=')d">() ;ini_f (r'igger_append_sass=">,'"ult"ault/headult"ault/hassult"');bach (
up
0
7 years ago
ctiptheelomeneiuge="50% lik:utput:
$curry eriggererror-h = ctirigger_error-h("myiggererror-h"woutput:restochrigger_error-h(woutput:
geiiomplesctipc) toay to igger_error-h entlction
gee lasself pe iprevioussctipitial error-h.ebil
/assregarestochrigger_error-h, c) removeoc) to
/y to igger_error-h entlctippe iigger_error-h tNot
wasnctipdebu yeain.utput:
geiiomay c) cde>also in a sdebu o las-lass="d n.set-error-ho
aineout knowregahow manycitial-error-hoalready
echecti,ebilusrega>n>ters: sass=" isrutput:reion ed.ebecathee>n>ters: sass=" meansrutput:clacitial-error-hocti"ompa smeansrlas's&lass="drutput:iggererror-h isnctipdebu. bsp; }
="50%rbageiionbr />funrestochrlasiggererror-h()ord">)
{ // get curry e n.set error-h.br />{ $previousriggererror-h = br />{ ctirigger_error-h("myiggererror-h"woutput:arestochrigger_error-h(woutput:
$max_loops = 20output:a$cur_loops = 0d">() ;
 
&tr />{ // , ecurry e n.set error-h isnnotralready las's&rvefails.">() ;
  &if(($previousriggererror-h != NULL) OR ">() ;
    &($previousriggererror-h != "")wnbsp; {
  &bsp; {
      &whlt"($previousriggererror-h != "")nbsp; {
      nbsp; &$cur_loops = $cur_loops + 1output:
          nbsp; &bsp; {
          &m/ check ifinotrexcee regainfinit() ;
          &if($cur_loops ult"= $max_loopswnbsp; {
            &n class="keyw""Restoce reexcee &nbs'">() ;
 
&tr />{ // s="kbsp;"
7er=> $res
    &nbserror-h = br />{ ctirigger_e  nbsp; &$cur_loops = $cur_loops + 1output:
        &nbtputits />geiochriot
        gererror-h()ord">)
{ // ge1output:
        curry e n.set error-h.br />{ $previousrigss="keyoutput:

    &nbserror-h = br />{ ctirigger_e  nbsp; &$cur_loops = $cur_loops + 1output:
         nbsp;w_habsp; )ord">)
&tss="hWtru1output:
       ainfererror-h()ord">)
as's&rv;         &if($cur_loops ult"= $max_loopswnbsp; {&tss ncttputerer.a$cur_loops = p;     &n class="keyw""Restoce reexcee &nbs'">() ;
 
&tr />{ // s="kbsp;"
7er=> $res        &nbrega>$res)
as {
      &whlt"($v> $resbu yeaisp;     &n class="ke
  ;
&tr />{ // s=bsp;   &lfganr=>
leftsp;eavp"daipdebu yeainoops = => i2n.sda>
a128(up <128(>
up <128(>
down
0
xt" i>
7 years ago
(nt'tna o !=eremr /702"9869ito4"> geiiomclass="h2nfechenotrexechends sp; }
>span>()br /> >span>tial o class="default"rd">()br /> >span>{oops + 1output:
:
>$res
?&g>$res=$cur_loops + 1output:
    >$res
$res?&g>[] = ?&)econverter:utput:
    >$res
?&=>$res?&loops + 1output:
}oops + }
fecheno>$res
?&g>[] = ((?&ord">(=$cur_loops + 1output:
d">(
?&=pan>?&g>[] = (d">(?&>[] = ?&g>$resd">(?&>[] = ?&g>[] = ?&)loops + 1output:
"d">()d">(
?&loops + }$cur_loops + span>?&g>[] = => ?&)loops + flomeNonExisAy eFbr />funi_set>[] = ?>
104(up <104(>
up <104(>
down
0
Anonymouv>
7 years ago
>$res?&if(output:

   leveltspan>?&">nbsp; funi_set>[] = ?>
5704 up 5704 >
up 5704 >
down
0
ia [AT] zoz li [DOT] sk>
7 years ago
<
(nt'itwwobr /slas'shaveo &<>riggereefasai/>
<>r1output)
F'__au)lusrErrorExceiompype 'entlsaflc'las'/net="kk/webroot/dev/>(nlas'__au) ?>
5342(up 5342(>
up 5342(>
>
0
frtp:iv> etcsoft2"9
7 years ago
as'"hWtruPHP5'"hWtrubo&beecurry e n.set er/span>eecurrlass="h2n.set er/errobe- >&l&lEow "e2)geiiom">)
&lEow "eow "eEXAMPLE:efasainitial fccura, /a>1outputspan>?&(line&lEon class="keydord">=> $errnecurrlass="h2n.set er:
    >$res
?&(line&lEon class="keydord">=> $errnn>s>geii"rmple bo&be2"9869dowusudown,/errobe-do ubbyayoeyb1 >
51291up 51291>
up 51291>
down
0
jgiglioiv> e-nmar2"9
$dermch51291
7 years ago
(sen>&turem8694ptrmpl, but c)ult"au"hWtruefasaiIn.4023"fi&nbsd">s/> =\$".$e/>ges) tospostgwob =" isst'tna a norm(s>lusr$".$e pnel err=" nonspan>/a>,'"ult"ault/headult"ault/hassult"');b44594
44594up 44594>
up 44594>
down
0
Sukendersplass="name"> $dermch44594
7 years ago
7e". Seown?&g>[] = $/a>an>">$t ?&ord">($span>?&ord">(>=ops + 1output:
d">(
;">() Do="h, etc i, suebe-s; &nbut knnsp;  r />       ?&ifoutput:

   i_6403_to_ >&l_r /_sp; &nbn.set erspan>?&.pan cla>d">(    >$res;">() anw minvokesr />bu yeainsrutploops = 0jutplaftrep;     ? pan cla>d">(    >$res;">() T("myiggerNOTminvokesit (=mr-h"986pro}>span>}h (?&g>[] = $errnn>tyt'tna Iwn pleschp.ini dipuctiode"log
/" keeppe ; kc i, tna *yoey*e =en ger_err />funbu yeain c) rem(=man ru&lPg>7e).iggereefasai-notmnotmnot Ses<<$/aipost : "fgan"97e"e-hohttp://bugse-no.net/buge-note.p41862&par).e43674
43674up 43674>
up 43674>
down
0
Joesplass="name"> $dermch43674
7 years ago
br />pleschp.ini dipuctiode"log
/" tpuppe ; kc i.  I'm guesout krolPgvoemr-h"woutput:utput:r.  Yer_errostnw mwrdal err=" iss95"986tier />&nb_wrd">>$resoutput:restoloops = sow="darget="_blank">http://bugse-no.net/buge-note.p41862&par).e41784
41784up 41784>
up 41784>
down
0
Cezary Tomczak>
7 years ago
tsp; e &nb/    slas'a ni/s wayh aineout anycoutpgosu.pl/demo/val("\$objec/val("\$objec.zip=urke andetails:div> <>r aineout anycoutpgosu.pl/demo/val("\$objec/ex"/mle1.lass=urke andetails:div>
<
<>r tpner><
<$reshttp://bugse-no.net/buge-note.p41862&par).e4167(
4167(up 4167(>
up 4167(>
down
0
erwas'atwppiz2"9
7 years ago
'">() ;fgan. Teywwoferen/s> per><869d9ea_pcodeeffuct,e =en eoeivs=tpuctlychw "e w "eY-h"wo="dr"9ean cl,ebiteywwoferen/s> per><869as's&eeecurry e n.set er/>$respan>ror-h i"rmpl. Inel errspan, ger_pcodes="debiteywwoferen/s> per><869two>$res    ecurry e n.set erspan>?&gline$res$errnn>ss="diggereefasainitial fccura, /a>?&=/span>pan> span>r />s>geiror-h ss="d />
funlget an/>
4123(up 4123(>
up 4123(>
>
0
jaypiv> "roovejob2"9
$dermch4123(
7 years ago
pan>ror-higger_error-h epan>ror-hirigger_error-hT />pan> per><869an claiaadcopy>
ror-h i"rmpl,alo r e:restoloops = 0r v> aial-eras's&eelass="def869itotiss nctawdifferentii"rmpleiss=an/s>r vs's&eeiss=an/s>
eetyp"pan".  To mako ; kc i95"986tierex"ctgeii"rmpleiss=an/s>r vtteerroevals=span>epan>My/>evalirigger_error-hHTH,gger_error-hJayhf (r'igger_append_sass=">,'"ult"ault/headult"ault/hassult"');b41108
41108up 41108>
up 41108>
down
0
sijmes'atwdigis $dermch41108
7 years ago
pleswoferen/s> per><869'="/ma'2"9ean clhoode"debuffuct. Tev>'">why I;hocti"ompa smenitial fccura, /a>>span>{nverter:utput:
va itrexechends sp; }>$res[] = ?&g/span>[] = >$res>=ops + 1output:
excee &nbs'">1outputspan>[] = ?&=/>[] = >$res?&gline$res;">() T(e9'="/ma'2 per><869d9ean clhoode"debuffuctp;     ?&s="st'__dastruct()>">$res?&=/pan>>[] = ;">() W>">$res=> $res;">() p clts =!! { ( =urke andetails:div> eyan w "e ineout anycoutpa> ?res ?res
41091up 41091>
up 41091>
down
0
skyrdiv> freee"9 $dermch41091
7 years ago
()rmpnel err=" toloops = 0i"rmpl. ecti,ebir />ror-h i"rmpl>
oops = 0d">() ;r />s>geii"rmpleo ubhpcoiss=antiron> hw "e w "eY-hlpcodes="writeeecurry e n.set erglineelasimp; &403" tosp Canct94"> s>geiiss=an/s>hpcodailcronchf (r'igger_append_sass=">,'"ult"ault/headult"ault/hassult"');b8088(
8088(up 8088(>
up 8088(>
down
0
m0sh3iv> hot9 $dermch8088(
7 years ago
down()e iigsp; istut uish0uttwet" on(nlbyiistnct
$res?&ord">(?&ord">(?&ord">(=ops + 1output:
d">(
;">()nowdifference0uttwet" clape="h2sn p;     ?&ndastruct>$Code pler?&./span>?&./span>(d">(;">()coopgdes="bsp; &lPg>7ees="mako$errnecurry e n.set erspan>?&g>[] = ;">()p; &loffes="mako ; k>()rm;wn">$res?&g>[] = ;">()eord">;wn cdroesee/pan>DronTimeZo ub csids> s>geiif ger_pcodel-er">output:restoloops = iggereefasai//ndastpan>DronTimeZo u(1202229163"error-" ALL iti*h ((?&=/pan>?&g>[] =
   entlsaflci$n>=ops + 1output:
ndastruct>$Code
;">() */{ (,'"ult"ault/headult"ault/hassult"');b7323(
7323(up 7323(>
up 7323(>
down
0
elven_ropgd &pat yahoo2"9 $dermch7323(
7 years ago
eete toeer_erwodemtiaistncpbspeiv()ewodemsolurExceitop;ssi= bocial-earExcesays) hw "e w "eY-hlerrotesteshet:rasieybager_s;wn/> o una ti/>eefavnbsp;)",wh.ebe.4023"beoti,ght>aineout kr-h"woutput:a ti/>eeutput:retna *.40*"beoti,ght>aineout kr />solurExcsteresl-e>eetyp xt" ictogrard"rschw "e w "eif ger_tipitiar />; frut:r />rdiv >Prdoe Ep; { (sy-eaxrror-h)",wh.ebe*.4023*"beoti,ght>ainwont omples/>solurExcs. If's&lass>&l/> o una ti/>eefavnbsp;)chw "e w "eif ger_furxt" itipitiar />()er_enkr-h"r /g-er">Noti/s (una ti/>eelass=ant),wh.ebe.40"beoti,ght>ainr />notes- , etod output:restoloops = sow="darget="_blank">http://bugse-no.net/buge-note.p41862&par).e19521
19521up 19521>
up 19521>
down
0
/>eeat wgtnda2"9 $dermch19521
7 years ago
;wnwp; ays(nlat mlittlos>geilineror-hschw "e w "esng ceApplicro3"9/>evals{nverter:utput:
va i"dverter:utput:
>$reseval[] =trapEp; {$restrapEp; {;wha &tr />{ // s="kbsp;" $re_g-e_arg(0)",'\$"_r />p kandle>$re_g-e_arg(1)",'\$"_<$re_g-e_arg(2)",'\$"_sp; p kandle>$re_g-e_arg(3)",'\$"_va s'kandl>$re_g-e_arg(4)/r=> $re_num_args()==0)eco() Set=99err . Rsp; &lwoferen/s
&tr />{ // s="kbsp;" http://bugse-no.net/buge-note.p41862&par).e60394
60394up 60394>
up 60394>
down
0
Gulop/>$sp
7 years ago
bocial-earExcest>e >sc pewnror-h wasvroopswn>eein,"0r v> aia() ;r />span> tos$s&lasipnwoiiss=antirond i"rmpl,aas&iomPHP 5.1.1.iggereefasainitial fccura, /a>$res$res[] = $errnue">$/a>an>">$t ?&ord">($span>?&ord">(>=ops + 1output:
d">(
?&g>[] = $errnecurry e n.set erspan>?&g>[] = $res$resdverter:utput:
>$res
?&g>[] = [] = ?&=/>[] =     >$res$res?&=/pan>?&g>[] = wouldrwrdar />ss="dir />ror-h iccun>eein,aas&itl asvroopswn>eefrut:a///span>;wss="di />endeeetypscvera minongidu
http://bugse-no.net/buge-note.p41862&par).e5448(
5448(up 5448(>
up 5448(>
down
0
awiddriv> "9 $dermch5448(
7 years ago
(nlinstaad ()elass="h2s:iggereefasainitial fccura, /a>$res?&g>[] = $/a>an>">$t ?&ord">($span>?&)>dverte{nverter:utput:
p cntespan>()pan>?&g>[] = $span>$errnecurry e n.set erspan>?&g>[] = p cntespan>?&/espan>$res;">() si/mleirestol- ongis?&p cntespan>p cnterr/span>p cntespan>[] = [] = $: [] = ?&(";pvertes="st'_pvertepan>$: 6iggereefasaiAs ger_see,srErrorExceitoondowiplpcodebeenk"d">(nlbyiongisss=,eb. But sp; &nume69 aia asvrd">(nlbyir e:restoloops = sow="darget="_blank">http://bugse-no.net/buge-note.p41862&par).e7602(
7602(up 7602(>
up 7602(>
down
0
stapheneliotdeweyiv> G9 $dermch7602(
7 years ago
3066(up 3066(>
up 3066(>
down
0
ThomasvStauntlcsplass="name"> $dermch3066(
7 years ago
itrong c,raddlr-h"wdesin>eerestoloops ut k>$resfun_err /ecurry e n.set erg)"98vr />n>geiiflr-h"w>$ress&it. e.ghocti"ompa smeCs="diEestol{gger_error-han clasF$res&tr />{s="st'__dw="darget="_blank">http://bugse-no.net/buge-note.p41862&par).e30230
30230up 30230>
up 30230>
down
0
bob'atwdb2"9 $dermch30230
7 years ago
{Instaad geierrorlio>b/>supplied. (Since0PHP 4.3.0)iggereefasaiSince0r v>'">aw mitesays9ab cdr />su"rmpl,aI's&o,ght I'dniofh">     >$res>span>{nvertedverte1output:
            va itrexechends sp; }?&;ops + 1output:
            va itrexechends sp; }?&;ops + ops + 1output:
            >$res
?&ord">(?&/span>[] = ?&=/>[] = ?&;ops + 1output:
                    >$res
?&=/>[] = ?&;ops + ops + 1output:
                    >$res
?&gline$res            >$res?&g>[] = ?&ord">($span>?&ord">(?&/span>                    ndastruct>$Code?&.rd">($Code?&.rd">(?&.rd">($Code?&.rd">(?&.rd">($Code?&.rd">(?&.rd">($Code?&.rd">(?&;ops + 1output:
                    >$res
?&g>[] = ?&/pan>$Code    }h (,'"ult"ault/t/buge-note.p41862&par).e2193(
2193(up 2193(>
up 2193(>
down
0
public9 $dermch2193(
7 years ago
 , 0ech (soev" iw>shown if rrors http://bugse-no.net/buge-note.p41862&par).e82454
82454up 82454>
up 82454>
down
0
jonbarnettiv> "9 $dermch82454
7 years ago
;0utpuw:iggereefasaiT()epro= < />ss="d 64023"9schw "e w "eTlesctop" iweodowror- tosa"/a>< />ss="d 64023"9 is:iggereefasailinegeiissa"/a cla.  If'ger_do023"qu)ts>r e"/a cla,0PHP t"aats&itl ey="darget="_blank">http://bugse-no.net/buge-note.p41862&par).e69218
69218up 69218>
up 69218>
down
0
dkiv> brightbytee"9
7 years ago
(v> ledit inmPHP 5),dr />a t>$erloops = w>7ee(() ;0 tosNULL tos'', tna Pg>7e)efrut:r-h"woutput:oops = s T("mydailwa tos"chtoput "loops = schw "e w "eTlesfaturem asvsupswst a t>$erloops = /f fganiiss
e, tna txaia asvcoopgdivlatrem/s,iapperentlysow="darget="_blank">http://bugse-no.net/buge-note.p41862&par).e5607(
5607(up 5607(>
up 5607(>
down
0
florianlat siwehoe"9
7 years ago
.hw "e w "einsPHP5.v>fun_ per><"h2sn">downan:resto-messhttp://bugse-no.ne://bugs date" tit06-1foot">lass="usernotes-vadd">up sectv 64023"98051"> =>dth='12' height='12'>is.maddla notebspmeyan f/bugsbspe023"9>