Home > Back-end >  Php 8, how to ignore supressed errors from logging?
Php 8, how to ignore supressed errors from logging?

Time:03-13

This code represent a cache funcionality:

@ini_set('display_errors', '1');
error_reporting(-1);

set_error_handler(static function($errno, $errstr, $errfile, $errline, $vars = []) {
    if (error_reporting() === 0)
    {
        return;
    }
    echo 'ERROR: <pre>'; var_dump($errno, $errstr, $errfile, $errlne, $vars); echo '</pre>';
    return true;
});

echo "start\r\n";

$variable = @include('/none.txt');
if (!is_array($variable))
{
    $variable = [1,2,3];
}
file_put_contents('/none.txt', var_export($variable, true));

echo 'end';

this is a legit cache handling. If file doesnt exists, the value is not an array, therefore we can produce it and store. We also installed a fine-tuning error loggers.

At least, it used to be with Php 7.4

With php 8.1 the situation is more complicated, as it turned out that we cant distinquise supressed and actual error. Of course, I can rewrite it like that:

$variable = false;
if (is_file('/none.txt'))
{
    $variable = @include('/none.txt');
}
if (!is_array($variable))
{
    $variable = [1,2,3];
}
file_put_contents('/none.txt', var_export($variable, true));

the problem is, this version is not thread-safe. What if so many user loads the site and the none.txt gets erased by another thread? What if is_file() tells it exists, but by the time it reaches include() the file is gone? An error report will take place, and nobody will accept that "oh thats fine, its just "planetary alignment".

CodePudding user response:

You need to check if the error was silenced:


set_error_handler(static function($errno, $errstr, $errfile, $errline, $vars = []) {
    if (error_reporting() === 0)
    {
        return;
    }
    if (!(error_reporting() & $errno)) { // <--------------------------
        return false; // Silenced
    }
    echo 'ERROR: <pre>'; var_dump($errno, $errstr, $errfile, $errlne, $vars); echo '</pre>';
    return true;
});

As described in docs https://www.php.net/manual/en/language.operators.errorcontrol.php

See live https://3v4l.org/hd72W

  • Related