Search code examples
phpmysqlerror-handlingphp4

how to properly manage triggered errors in PHP4


m maintaining a project, that has to be compatible through PHP 4.X to 5.2. The project as several errors wich are not very well handled.

What I want to do is redirect user to a "nice" error page, and log the error in the database. In order to keep track of the user, the file, and the error message. Here is what I've tried so far:

set_error_handler("myErrorHandler");
/**
 *My function to handle errors
 */
function myErrorHandler( $errno , $errstr ,  $errfile="nofile" , $errline=0 , $errcontextArray=NULL ){
    session_start();
    if (!isset($errno)|!isset($errstr)) {
        exit(0);
    }
    if (!mysql_ping()) {
        require '../Connection/databaseinfo.php';
    }
    $id_user = $_SESSION['ident'];
    $errstr = GetSQLValueString($errstr, "text");
    $errfile = GetSQLValueString($errfile, "text");
    $errline = GetSQLValueString($errline, "int");
    $sql = "insert into error_history 
        (id_user, message, file, line)
        values ($id_user, $errstr, $errfile, $errline)";
    mysql_query($sql) or die (mysql_error());

//    header("location:error.php"); ---> I can't (see comment below)
    echo "<script type='text/javascript'> window.location.href='error.php';</script>";//Redirection dégueulasse //TODO: trouver mieux
    return true;
}

Why not header()? Because the error can be triggered anywhere in a page, and thus, having the headers already sent.

Why not header() along with obstart(), ob_flush()? Because there are lot of pages already in production, and I can't modify them all.

My questions are:

  1. Am I doing it wrong?
  2. Is there a better way to handle the redirection?

Solution

  • This is how to handle fatal errors in php 5.2:

    <?php
    register_shutdown_function('shutdownFunction');
    function shutDownFunction() {
        $error = error_get_last();
        if($error['type'] >= 1){
            mail('[email protected]', 'Error: XY',"Error msg:"."Server Error:".implode("\n", $error));
        }
    }
    ?>