PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

debug_backtrace> <enchant_dict_suggest
Last updated: Tue, 27 Nov 2007

view this page in

Funciones de Gestión de Errores y Registros

Introducción

Estas son funciones que trabajan en la gestión de errores y registros. Le permiten definir sus propias reglas de gestión de errores, asi como modificar el modo en que los errores son registrados. Esto le permite modificar y mejorar el reporte de errores para que se adapte a sus necesidades.

Con las funciones de registro, puede enviar mensajes directamente a otras máquinas, a un correo electrónico (¡o correo electrónico a una puerta de enlace con un buscapersonas!), a bitácoras del sistema, etc., de modo que puede registrar y monitorear selectivamente las partes más importantes de sus aplicaciones y sitios web.

Las funciones de reporte de errores le permiten personalizar el nivel y tipo de retroalimentación de errores que PHP entrega, desde noticias simples a funciones personalizadas devueltas durante los errores.

Requisitos

No se necesitan bibliotecas externas para construir esta extensión

Instalación

No se necesita ninguna instalación para usar estas funciones, son parte del núcleo de PHP.

Configuración en tiempo de ejecución

El comportamiento de estas funciones está afectado por los valores definidos en php.ini.

Opciones de Configuración de Errores y Registro
Nombre Por defecto Modificable Cambios
error_reporting NULL PHP_INI_ALL  
display_errors "1" PHP_INI_ALL  
display_startup_errors "0" PHP_INI_ALL Disponible desde PHP 4.0.3.
log_errors "0" PHP_INI_ALL  
log_errors_max_len "1024" PHP_INI_ALL Disponible desde PHP 4.3.0.
ignore_repeated_errors "0" PHP_INI_ALL Disponible desde PHP 4.3.0.
ignore_repeated_source "0" PHP_INI_ALL Disponible desde PHP 4.3.0.
report_memleaks "1" PHP_INI_ALL Disponible desde PHP 4.3.0.
track_errors "0" PHP_INI_ALL  
html_errors "1" PHP_INI_ALL PHP_INI_SYSTEM en PHP <= 4.2.3. Disponible desde PHP 4.0.2.
docref_root "" PHP_INI_ALL Disponible desde PHP 4.3.0.
docref_ext "" PHP_INI_ALL Disponible desde PHP 4.3.2.
error_prepend_string NULL PHP_INI_ALL  
error_append_string NULL PHP_INI_ALL  
error_log NULL PHP_INI_ALL  
warn_plus_overloading NULL   Esta opción ya no se encuentra disponible a partir de PHP 4.0.0
For further details and definitions of the PHP_INI_* constants, see the Directivas de php.ini.

A continuación se presenta una corta explicación de las directivas de configuración.

error_reporting integer

Establece el nivel de reporte de errores. Este parámetro es, o bien un entero que representa un campo de bit, o constantes con nombre. Los niveles de error_reporting y las constantes están descritas en Constantes Predefinidas, y en php.ini. Para definir este valor en tiempo de ejecución, use la función error_reporting(). Vea también la directiva display_errors.

En PHP 4 y PHP 5, el valor predeterminado es E_ALL & ~E_NOTICE. Este valor no muestra errores de nivel E_NOTICE. Puede que usted quiera mostrarlos durante su actividad de desarrollo.

Note: Al habilitar E_NOTICE durante el desarrollo de software tiene algunos beneficios. Para propósitos de depuración: los mensajes NOTICE le advertirán sobre posibles fallos en su código. Por ejemplo, se le advertirá sobre el uso de valores no-asignados. Es extremadamente útil para encontrar errores ortográficos y ahorrar tiempo de depuración. Los mensajes NOTICE le advertirán sobre el uso de un estilo incorrecto. Por ejemplo, $matriz[item] está mejor escrito como $matriz['item'] ya que PHP intenta darle a "item" un tratamiento de constante. Si no es una constante, PHP asume que es un índice de tipo cadena para la matriz.

Note: En PHP 5, un nuevo nivel de error, E_STRICT, se encuentra disponible. Dado que E_STRICT no se incluye en E_ALL, usted debe habilitar explícitamente este tipo de nivel de error. Habilitar E_STRICT durante el desarrollo tiene algunos beneficios. Los mensajes STRICT le ayudarán a usar los últimos y más grandiosos métodos sugeridos para escribir código, por ejemplo, le advertirá sobre el uso de funciones obsoletas.

Note: Constantes PHP por fuera de PHP El uso de Constantes PHP por fuera de PHP, como en httpd.conf, no tendrán sentido, de modo que en tales ocasiones las valores integer son requeridos. Y dado que con el tiempo se agregarán niveles de error, el valor máximo (para E_ALL) probablemente cambie. Así que en lugar de E_ALL considere usar un valor grande para cubrir todos los campos de bits de ahora y hacia el futuro, un valor numérico como 2147483647.

En PHP 3, el valor predeterminado es (E_ERROR | E_WARNING | E_PARSE), lo que en la práctica representa lo mismo. Note, sin embargo, que dado que las constantes en el archivo php3.ini de PHP 3 no son soportadas, el valor de error_reporting allí debe ser numérico; por lo tanto, es 7.

display_errors string

Este parámetro determina si los errores deben ser puestos en pantalla como parte de la salida o si deben ser ocultados al usuario.

El valor "stderr" envía los errores a stderr en lugar de stdout. Este valor está disponible a partir de PHP 5.2.4. En versiones anteriores, esta directiva era de tipo boolean.

Note: Es una característica de apoyo para su proceso de desarrollo y no debería ser usada nunca en sistemas en producción (p.ej. sistemas conectados a internet).

Note: Aunque display_errors puede ser definido en tiempo de ejecución (con ini_set()), no tendrá ningún efecto si el script contiene errores fatales. Esto se debe a que la acción de tiempo de ejecución deseada no se alcanza a ejecutar.

display_startup_errors boolean

Aun cuando display_errors esté encendido, los errores que ocurren durante la secuencia de arranque de PHP no son desplegados. Es muy recomendable mantener display_startup_errors apagado, excepto en tiempos de depuración.

log_errors boolean

Indica si los mensajes de error de un script deben ser registrados en la bitácora de errores del servidor o error_log. Esta opción es por lo tanto espocífica al servidor.

Note: Es altamente recomendable que use registro de errores en lugar de despliegue de errores en sitios web en producción.

log_errors_max_len integer

Establece la longitud máxima de log_errors en bytes. En error_log se añade información sobre la fuente. El valor por defecto es 1024, y un valor de 0 permite que no se aplique ninguna longitud máxima en absoluto. Esta longitud se aplica también a los errores almacenados en el registro, a los errores que se despliegan y a $php_errormsg.

Cuando se usa un número entero, el valor del mismo es medido en bytes. También se puede usar la notación reducida tal como se describe en esta FAQ.
ignore_repeated_errors boolean

No registrar mensajes repetidos. Los errores repetidos deben ocurrir en el mismo archivo, en la misma línea hasta que el parámetro ignore_repeated_source sea establecido como true.

ignore_repeated_source boolean

Ignorar la fuente de mensaje cuando se ignoran los mensajes repetidos. Cuando este parámetro está encendido, no se registrará errores con mensajes repetidos desde diferentes fuentes de archivos.

report_memleaks boolean

Si este parámetro está apagado, entonces las fugas de memoria no serán mostradas (en stdout o en el registro). Este valor sólo tiene efecto en una compilación de depuración, y si error_reporting incluye E_WARNING en la lista permitida.

track_errors boolean

Cuando está habilitado, el último mensaje de error estará siempre presente en la variable $php_errormsg.

html_errors boolean

Permite deshabilitar las etiquetas HTML en los mensajes de error. El nuevo formato para los errores en HTML produce mensajes con enlaces que dirigen al usuario a una página que describe el error o función que ha causado el error. Estas referencias son afectadas por docref_root y docref_ext.

docref_root string

El nuevo formato de error contiene una referencia hacia una página que describe el error o la función que ha causado el error. En el caso de páginas de un manual, usted puede descargar el manual en su idioma y establecer esta directiva ini como la URL de su copia local. Si su copia local del manual puede encontrarse bajo '/manual/' entonces puede usar simplemente docref_root=/manual/ . Adicionalmente debe establecer un valor de docref_ext que coincida con las extensiones de archivo de su copia; docref_ext=.html . Es posible usar referencias externas. Por ejemplo, puede usar docref_root=http://manual/en/ o docref_root="http://landonize.it/?how=url&theme=classic&filter=Landon &url=http%3A%2F%2Fwww.php.net%2F" .

Por lo general usted querrá que el valor de docref_root finalice con una barra '/'. Pero observe el segundo ejemplo mencionado anteriormente, el cual no tiene una barra final, ni la necesita.

Note: Esta es una característica de apoyo para su desarrollo ya que permite consultar la descripción de una función fácilmente. Sin embargo, nunca debe ser utilizada en sistemas en producción (p.ej. sistema conectados a internet).

docref_ext string

Vea docref_root.

Note: El valor de docref_ext debe comenzar con un punto '.'.

error_prepend_string string

Cadena a mostrar antes de un mensaje de error.

error_append_string string

Cadena a mostrar después de un mensaje de error.

error_log string

Nombre del archivo en donde deberían registrarse los errores del script. El archivo debe tener permisos de escritura para el usuario del servidor web. Si se utiliza el valor especial syslog, los errores son enviados al gestor de registros del sistema. En Unix, esto quiere decir syslog(3) y en Windows NT quiere decir el "event log". El gestor de registro de actividades no está soportado bajo Windows 95. Vea también: syslog(). Si esta directiva no está definida, los errores son enviados al registro de errores SAPI. Por ejemplo, puede ser un registro de errores en Apache o stderr en CLI.

warn_plus_overloading boolean

Si se habilita, esta opción hace que PHP genere una advertencia cuando se utilice un operador más (+) con cadenas. Esto facilita la labor de encontrar scripts que necesitan ser reescritos para hacer uso del concatenador de cadenas en su lugar (.). Esta opción no existe a partir de PHP 4.

Constantes predefinidas

Las constantes listadas aqui están siempre disponibles a través del "núcleo PHP".

Note: Es posible usar estos nombres de constantes en php.ini pero no por fuera de PHP, como en httpd.conf, en donde debería usar los valores de máscara de bits en su lugar.

Errores y Registro
Valor Constante Descripción Nota
1 E_ERROR (integer) Errores fatales en tiempo de ejecución. Estos indican errores de los que no es posible recuperarse, tales como problemas de asignación de memoria. Se detiene la ejecución del script.  
2 E_WARNING (integer) Advertencias en tiempo de ejecución (errores no-fatales). La ejecución del script no se interrumpe.  
4 E_PARSE (integer) Errores de intérprete en tiempo de compilación. Esto tipo de errores deberían ser generados únicamente por el interprete.  
8 E_NOTICE (integer) Anotaciones en tiempo de ejecución. Indican que el script se ha topado con algo que puede indicar la presencia de un error, pero que también podría ocurrir en el curso normal de la ejecución de un script.  
16 E_CORE_ERROR (integer) Errores fatales que ocurren durante el arranque inicial de PHP. Es como un E_ERROR, excepto que es generado por el núcleo de PHP. a partir de PHP 4
32 E_CORE_WARNING (integer) Advertencias (errores no-fatales) que ocurren durante el arranque inicial de PHP. Es como un E_WARNING, excepto que es generado por el núcleo de PHP. a partir de PHP 4
64 E_COMPILE_ERROR (integer) Errores fatales en tiempo de compilación. Es como un E_ERROR, excepto que es generado por el Motor de Scripting de Zend. a partir de PHP 4
128 E_COMPILE_WARNING (integer) Advertencias en tiempo de compilación (errores no fatales). Es como un E_WARNING, excepto que es generado por el Motor de Scripting de Zend. a partir de PHP 4
256 E_USER_ERROR (integer) Mensaje de error generado por el usuario. Es como un E_ERROR, excepto que es generado desde código PHP usando la función trigger_error(). a partir de PHP 4
512 E_USER_WARNING (integer) Mensaje de advertencia generado por el usuario. Es como un E_WARNING, excepto que es generado desde código PHP usando la función trigger_error(). a partir de PHP 4
1024 E_USER_NOTICE (integer) Anotación generada por el usuario. Es como un E_NOTICE, excepto que es generado desde código PHP usando la función trigger_error(). a partir de PHP 4
2048 E_STRICT (integer) Noticias de tiempo de ejecución. Habilite este valor para hacer que PHP sugiera cambios en su código que velarán por la mejor interoperabilidad y por mantener la compatibilidad de su código. a partir de PHP 5
4096 E_RECOVERABLE_ERROR (integer) Error fatal atrapable. Indica que ocurrió un error probablemente peligroso, pero no ha dejado el Motor en un estado inutilizable. Si el error no es atrapado por un gestor definido por el usuario (vea también set_error_handler()), la aplicación aborta como si fuera un E_ERROR. a partir de PHP 5.2.0
8191 E_ALL (integer) Todos los errores y advertencias, en la medida en que sean soportados, excepto por el nivel E_STRICT en PHP < 6. 6143 en PHP 5.2.x y previamente 2047

Los valores referidos anteriormente (ya sean numéricos o simbólicos) son usados para construir una máscara de bits que indica cuáles errores reportar. Puede usar los operadores bit a bit para combinar estos valores o excluir explícitamente ciertos tipos de errores. Sin embargo, note que únicamente '|', '~', '!', '^' y '&' serán entendidos desde php.ini, y que ningún operador bit a bit será interpretado correctamente desde php3.ini.

Ejemplos

A continuación podemos apreciar un ejemplo del uso de las capacidades de gestión de errores que vienen con PHP. Definimos una función de manipulación de errores que registra la información en un archivo (usando un formato XML), y envía un correo electrónico al desarrollador en caso de que un error crítico en la lógica del software ocurra.

Example#1 Uso de gestión de errores en un script

<?php
// haremos nuestra propia manipulación de errores
error_reporting(0);

// función de gestión de errores definida por el usuario
function gestorDeErroresDeUsuario($num_err$mens_err$nombre_archivo,
                                  
$num_linea$vars)
{

    
// marca de fecha/hora para el registro de error
    
$dt date("Y-m-d H:i:s (T)");

    
// definir una matriz asociativa de cadenas de error
    // en realidad las únicas entradas que deberíamos
    // considerar son E_WARNING, E_NOTICE, E_USER_ERROR,
    // E_USER_WARNING y E_USER_NOTICE

    
$tipo_error = array (
                
E_ERROR              => 'Error',
                
E_WARNING            => 'Advertencia',
                
E_PARSE              => 'Error de Intérprete',
                
E_NOTICE             => 'Anotación',
                
E_CORE_ERROR         => 'Error de Núcleo',
                
E_CORE_WARNING       => 'Advertencia de Núcleo',
                
E_COMPILE_ERROR      => 'Error de Compilación',
                
E_COMPILE_WARNING    => 'Advertencia de Compilación',
                
E_USER_ERROR         => 'Error de Usuario',
                
E_USER_WARNING       => 'Advertencia de Usuario',
                
E_USER_NOTICE        => 'Anotación de Usuario',
                
E_STRICT             => 'Anotación de tiempo de ejecución',
                
E_RECOVERABLE_ERROR  => 'Error Fatal Atrapable'
                
);
    
// conjunto de errores de los cuales se almacenará un rastreo
    
$errores_de_usuario = array(E_USER_ERRORE_USER_WARNINGE_USER_NOTICE);

    
$err "<errorentry>\n";
    
$err .= "\t<datetime>" $dt "</datetime>\n";
    
$err .= "\t<errornum>" $num_err "</errornum>\n";
    
$err .= "\t<errortype>" $tipo_error[$num_err] . "</errortype>\n";
    
$err .= "\t<errormsg>" $mens_err "</errormsg>\n";
    
$err .= "\t<scriptname>" $nombre_archivo "</scriptname>\n";
    
$err .= "\t<scriptlinenum>" $num_linea "</scriptlinenum>\n";

    if (
in_array($num_err$errores_de_usuario)) {
        
$err .= "\t<vartrace>" wddx_serialize_value($vars"Variables") . "</vartrace>\n";
    }
    
$err .= "</errorentry>\n\n";

    
// para efectos de depuración
    // echo $err;

    // guardar en el registro de errores, y enviar un correo
    // electrónico si hay un error crítico de usuario
    
error_log($err3"/usr/local/php4/error.log");
    if (
$num_err == E_USER_ERROR) {
        
mail("phpdev@example.com""Error Crítico de Usuario"$err);
    }
}


function 
distancia($vect1$vect2)
{
    if (!
is_array($vect1) || !is_array($vect2)) {
        
trigger_error("Parámetros incorrectos, se esperan matrices"E_USER_ERROR);
        return 
NULL;
    }

    if (
count($vect1) != count($vect2)) {
        
trigger_error("Los vectores deben ser del mismo tamaño"E_USER_ERROR);
        return 
NULL;
    }

    for (
$i=0$i<count($vect1); $i++) {
        
$c1 $vect1[$i]; $c2 $vect2[$i];
        
$d 0.0;
        if (!
is_numeric($c1)) {
            
trigger_error("La coordenada $i en el vector 1 no es un ".
                          
"número, se usará cero",
                            
E_USER_WARNING);
            
$c1 0.0;
        }
        if (!
is_numeric($c2)) {
            
trigger_error("La coordenada $i en el vector 2 no es un".
                          
"número, se usará cero",
                            
E_USER_WARNING);
            
$c2 0.0;
        }
        
$d += $c2*$c2 $c1*$c1;
    }
    return 
sqrt($d);
}

$gestor_de_errores_anterior set_error_handler("gestorDeErroresDeUsuario");

// constante indefinida, se genera una advertencia
$t NO_ESTOY_DEFINIDA;

// definir algunos "vectores"
$a = array(23"foo");
$b = array(5.54.3, -1.6);
$c = array(1, -3);

// generar un error de usuario
$t1 distance($c$b) . "\n";

// generar otro error de usuario
$t2 distance($b"no soy una matriz") . "\n";

// generar una advertencia
$t3 distance($a$b) . "\n";

?>

Ver también

Vea también syslog().

Table of Contents



debug_backtrace> <enchant_dict_suggest
Last updated: Tue, 27 Nov 2007
 
add a note add a note User Contributed Notes
Errores y Registro
jbq at caraldi dot com
15-Nov-2007 03:50
Precision about error_log when configured with syslog: the syslog() call is done with severity NOTICE.
mike at stroke7 dot lovehamhatespam dot com
11-Oct-2007 09:53
To add to Stephen's note about logging, I found that if I defined the error_log path to be the Apache error log folder (ie:  /var/log/httpd/php_error_log), it would still log to Apache's log, not the file I defined.

However, as soon as I moved the log to a location outside of the Apache error log folder, Apache obeyed my php.ini setting and began logging to the file I defined (ie: /var/log/php/php_error_log).

Platform: RHEL 4, Apache 2.0.55, PHP 5.2.2
tswaesch
12-Apr-2007 03:51
In Addition to the hint according error_reporting and display_errors in case that there is a global restriction that prevents showing the errors.

I tried the example of "petrov dot michael () gmail com" like this

<?php
ini_set
('display_errors','1');
ini_set('display_startup_errors','1');
error_reporting (E_ALL);

include(
'index.php');

?>

and it works great, but first I tried it without using the "include"-part. I pasted all at the beginning of my index.php and started it. This will NOT work.

Its highly IMPORTANT that the code to prove is included afterwards.

Hope it helps to prevent more #?!@%! errors. :-)=
Stephen
19-Jan-2007 01:29
If you are using PHP as an Apache module, your default behavior may be to write PHP error messages to Apache's error log. This is because the error_log .ini directive may be set equal to "error_log" which is also the name of Apache's error log. I think this is intentional.

However, you can separate Apache errors from PHP errors if you wish by simply setting a different value for error_log. I write mine in the /var/log folder.
petrov dot michael () gmail com
16-Jan-2007 09:11
I have found that on servers that enforce display_errors to be off it is very inconvenient to debug syntax errors since they cause fatal startup errors. I have used the following method to bypass this limitation:

The syntax error is inside the file "syntax.php", therefore I create a file "syntax.debug.php" with the following code:

<?php
error_reporting
(E_ALL);
ini_set('display_errors','On');

include(
'syntax.php');
?>

The 5 line file is guaranteed to be free of errors, allowing PHP to execute the directives within it before including the file which previously caused fatal startup errors. Now those fatal startup errors become run time fatal errors.
mortonda at dgrmm dot net
09-Jan-2007 03:16
Note the example code listed here calls date() every time this is called.   If you have a complex source base which calls the custom error handler often, it can end up taking quite a bit of time.  I ran a profiler on som code and discovered that 50% of the time was spent in the date function in this error handler.
theotek AT nowhere DOT org
04-Aug-2006 06:40
It is totally possible to use debug_backtrace() inside an error handling function. Here, take a look:

<?php
set_error_handler
('errorHandler');

function
errorHandler( $errno, $errstr, $errfile, $errline, $errcontext)
{
  echo
'Into '.__FUNCTION__.'() at line '.__LINE__.
 
"\n\n---ERRNO---\n". print_r( $errno, true).
 
"\n\n---ERRSTR---\n". print_r( $errstr, true).
 
"\n\n---ERRFILE---\n". print_r( $errfile, true).
 
"\n\n---ERRLINE---\n". print_r( $errline, true).
 
"\n\n---ERRCONTEXT---\n".print_r( $errcontext, true).
 
"\n\nBacktrace of errorHandler()\n".
 
print_r( debug_backtrace(), true);
}

function
a( )
{
 
//echo "a()'s backtrace\n".print_r( debug_backtrace(), true);
 
asdfasdf; // oops
}

function
b()
{
 
//echo "b()'s backtrace\n".print_r( debug_backtrace(), true);
 
a();
}

b();
?>

Outputs:

<raw>

Into errorhandler() at line 9

---ERRNO---
8

---ERRSTR---
Use of undefined constant asdfasdf - assumed 'asdfasdf'

---ERRFILE---
/home/theotek/test-1.php

---ERRLINE---
23

---ERRCONTEXT---
Array
(
)

Backtrace of errorHandler()
Array
(
    [0] => Array
        (
            [function] => errorhandler
            [args] => Array
                (
                    [0] => 8
                    [1] => Use of undefined constant asdfasdf - assumed 'asdfasdf'
                    [2] => /home/theotek/test-1.php
                    [3] => 23
                    [4] => Array
                        (
                        )

                )

        )

    [1] => Array
        (
            [file] => /home/theotek/test-1.php
            [line] => 23
            [function] => a
        )

    [2] => Array
        (
            [file] => /home/theotek/test-1.php
            [line] => 30
            [function] => a
            [args] => Array
                (
                )

        )

    [3] => Array
        (
            [file] => /home/theotek/test-1.php
            [line] => 33
            [function] => b
            [args] => Array
                (
                )

        )

)

</raw>

So, the first member of the backtrace's array is not really surprising, except from the missing "file" and "line" members.

The second member of the backtrace seem the be a hook inside the zend engine that is used to trigger the error.

Other members are the normal backtrace.
email_php_28429 at wg-karlsruhe dot de
20-Feb-2006 09:52
if you cannot use php 5+ and if you do not know, when your administrator/provider will update to a newer php-version, this could be interesting. otherwise it surely is not. ;-)

if you use the example above "example 1: using error handling in a script" with a php version prior to php 5, the part

<?php
$errortype
= array(
 
// ...
 
E_STRICT          => "Runtime Notice");?>

will throw a notice like
"Use of undefined constant E_STRICT - assumed 'E_STRICT'".

of course one could avoid this problem, with

<?php
if(defined('E_STRICT')) define('E_STRICT', 2048);
?>.

but this _could_ generate problems in future versions of php, if E_STRICT is set to 42 or something else.

for this reason i suggest

<?php
$errortype
= array(
 
E_ERROR           => 'error',
 
E_WARNING         => 'warning',
 
E_PARSE           => 'parsing error',
 
E_NOTICE          => 'notice',
 
E_CORE_ERROR      => 'core error',
 
E_CORE_WARNING    => 'core warning',
 
E_COMPILE_ERROR   => 'compile error',
 
E_COMPILE_WARNING => 'compile warning',
 
E_USER_ERROR      => 'user error',
 
E_USER_WARNING    => 'user warning',
 
E_USER_NOTICE     => 'user notice');
if(
defined('E_STRICT'))
 
$errortype[E_STRICT] = 'runtime notice';
?>.

<?php
// and instead of
// error_reporting(E_ALL | E_STRICT);
// one can use
error_reporting(E_ALL | (defined('E_STRICT')? E_STRICT : 0));
// to avoid that notice.
?>

prosit
seth
tracerdx at tracerdx dot com
29-Nov-2005 07:46
I keep seeing qualification lists for error types/error-nums as arrays; In user notes and in the manual itself. For example, in this manual entry's example, when trying to seperate behavior for the variable trace in the error report:

<?php //...

// set of errors for which a var trace will be saved
$user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE);

//and later...

if (in_array($errno, $user_errors)) {
   
//...whatever
}

//... ?>

I was under the impression that PHP error code values where bitwise flag values. Wouldn't bitwise masking be better? So I propose a slightly better way:
<?php //...

$user_errors = E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE;

//...blah...

if ($errno & $user_errors) {
   
//...whatever
}

//... ?>
Or for those of you who don't like the idea of using an integer as the condition in an if statement:

<?php
if (($errno & $user_errors) > 0) {
   
//...whatever
}
?>

I think that's much more efficient than using _yet another_ array() constuct and an in_array().

If I am wrong, and the E_* constants aren't supposed to be used in this fashion (ie, the constans aren't guaranteed to be bitwise, which would be odd since that's how they're setup in the php.ini file), then delete me. I just don't see why one should be using arrays when bitwise comparisons will work, considering the bitwise method should be MUCH more efficient.
giunta dot gaetano at sea-aeroportimilano dot it
23-Jun-2005 12:03
Something to take care of: if track_errors is enabled, $php_errormsg will always be populated with error messages of warning (and possibly notice?) level, regardless of the error_reporting level set.
21-May-2005 02:20
When configuring your error log file in php.ini, you can use an absolute path or a relative path.  A relative path will be resolved based on the location of the generating script, and you'll get a log file in each directory you have scripts in.  If you want all your error messages to go to the same file, use an absolute path to the file.

In some application development methodologies, there is the concept of an application root directory, indicated by "/" (even on Windows).  However, PHP does not seem to have this concept, and using a "/" as the initial character in a log file path produces weird behavior on Windows.

If you are running on Windows and have set, in php.ini:

  error_log = "/php_error.log"

You will get some, but not all, error messages.  The file will appear at

  c:\php_error.log

and contain internally generated error messages, making it appear that error logging is working.  However, log messages requested by error_log() do NOT appear here, or anywhere else, making it appear that the code containing them did not get processed.

Apparently on Windows the internally generated errors will interpret "/" as "C:\" (or possibly a different drive if you have Windows installed elsewhere - I haven't tested this).  However, the error_log process apparently can't find "/" - understandably enough - and the message is dropped silently.
shawing at gmail dot com
28-Jan-2005 12:05
Although the root user writes to the files 'error_log' and 'access_log', the Apache user has to own the file referenced by 'error_log = filename' or no log entries will be written.

; From php.ini
; Log errors to specified file.
error_log = /usr/local/apache/logs/php.errors

[root@www logs]$ ls -l /usr/local/apache/logs/php.errors
-rw-r--r--    1 nobody   root          27K Jan 27 16:58 php.errors
omega172 at yahoo dot com
21-Sep-2004 11:01
As pointed out previously, PHP by default logs to the Apache ErrorLog.

Beware: the messages it logs do not conform to Apache's error log format (missing date and severity fields), so if you use an automated parser on your error logs, you'll want to redirect PHP's errors somewhere else with the error_log directive.
ptah at se dot linux dot org
10-Sep-2004 03:20
PHP5 only (only tested with php5.0).

If you, for some reason, prefer exceptions over errors and have your custom error handler (set_error_handler) wrap the error into an exception you have to be careful with your script.

Because if you, instead of just calling the exception handler, throws the exception, and having a custom exception handler (set_exception_handler). And an error is being triggered inside that exception handler, you will get a weird error:
"Fatal error: Exception thrown without a stack frame in Unknown on line 0"

This error is not particulary informative, is it? :)

This example below will cause this error.
<?php
class PHPErrorException extends Exception
{
    private
$context = null;
    public function
__construct
       
($code, $message, $file, $line, $context = null)
    {
       
parent::__construct($message, $code);
       
$this->file = $file;
       
$this->line = $line;
       
$this->context = $context;
    }
};

function
error_handler($code, $message, $file, $line) {
    throw new
PHPErrorException($code, $message, $file, $line);
}

function
exception_handler(Exception $e)
{   
   
$errors = array(
       
E_USER_ERROR        => "User Error",
       
E_USER_WARNING        => "User Warning",
       
E_USER_NOTICE        => "User Notice",
        );
       
    echo
$errors[$e->getCode()].': '.$e->getMessage().' in '.$e->getFile().
       
' on line '.$e->getLine()."\n";
    echo
$e->getTraceAsString();
}

set_error_handler('error_handler');
set_exception_handler('exception_handler');

// Throw exception with an /unkown/ error code.
throw new Exception('foo', 0);
?>

There are however, easy fix for this as it's only cause is sloppy code.
Like one, directly call exception_handler from error_handler instead of throwing an exception. Not only does it remedy this problem, but it's also faster. Though this will cause a `regular` unhandled exception being printed and if only "designed" error messages are intended, this is not the ultimate solution.

So, what is there to do? Make sure the code in exception_handlers doesn't cause any errors! In this case a simple isset() would have solved it.

regards, C-A B.
pgerzsonr at freestart dot hu
11-Jan-2002 06:03
A handy errorhandler class can be found at:

http://phpclasses.upperdesign.com/browse.html/package/345

It has several enhancements (report layouts):

* prints the source code fragment where the error encountered,
* prints variable context around error source,
* suppresses error-messages, instead displays an arbitrary HTML or PHP page
* logging to multiple targets and autodetecting target logging
* error messages can be displayed in a separate browser window
* catching errors for runtime generated codes
* debugging variables.

debug_backtrace> <enchant_dict_suggest
Last updated: Tue, 27 Nov 2007
 
 
show source | credits | sitemap | contact | advertising | mirror sites