jayesh vekariya jayesh vekariya - 4 months ago 18
PHP Question

How to Handle Parse error using register_shutdown_function() in php?

I want to display php error using register_shutdown_function(), but using bellow script i can not handle Parse error:

<?php
register_shutdown_function('ShutDown');

echo "Hi" // generate error == Parse error: syntax error, unexpected 'echo' (T_ECHO), expecting ',' or ';' in file_naem on line 5;
echo "Hello";

?>


<?php

function catchError($errno, $errstr, $errfile = '', $errline = ''){

echo "Eroor Type : " .$errno. "<br>";
echo "Eroor Message : " . $errstr . "<br>";
echo "Line Number : " . $errline;
exit();
}
function ShutDown(){
$lasterror = error_get_last();
if(in_array($lasterror['type'],Array( E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR, E_CORE_WARNING, E_COMPILE_WARNING, E_PARSE))){
catchError($lasterror['type'],$lasterror['message'],$lasterror['file'],$lasterror['line']);
}
}
?>


How to Handle
Parse error
?

Answer

Parse errors can only be caught if they occur in scripts included or required. (also see http://stackoverflow.com/a/1900272/2123530)

So, sorry, this won't work the way you did it but can work this way :

<?php
register_shutdown_function('ShutDown');

include 'include.php'; 

function catchError($errno, $errstr, $errfile = '', $errline = ''){

    echo "Eroor Type : " .$errno. "<br>";
    echo "Eroor Message : " . $errstr . "<br>";
    echo "Line Number : " . $errline;
    exit();
} 
function ShutDown(){
    $lasterror = error_get_last();
    if(in_array($lasterror['type'],Array( E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR, E_CORE_WARNING, E_COMPILE_WARNING, E_PARSE))){
        catchError($lasterror['type'],$lasterror['message'],$lasterror['file'],$lasterror['line']);
    }
}   
?>

Content of include.php

<?php 
echo "Hi" // generate  error ==  Parse error: syntax error, unexpected 'echo' (T_ECHO), expecting ',' or ';' in file_naem on line 5;
echo "Hello";
?>