Search code examples
phploggingoperator-keyworderror-reporting

@ error suppression operator and set_error_handler


I am following good programming practices and I am logging the PHP errors to file instead of displaying it to user. I use set_error_handler() for that.

Now the problem. For example, I have somewhere:

@file_exists('/some/file/that/is/outside/openbasedir.txt');

But despite the error suppression operator, the error message logs. I don't want that. I want suppressed errors not to pass to my error handler.


Solution

  • This answer applies at PHP 7:

    The @ operator temporarily sets error_reporting to 0, so you can test the value of error_reporting in your error handler:

    if (error_reporting() == 0)
        return;
    

    Or even better, log only error types that are in error_reporting:

    $error_reporting = error_reporting();
    if ( !($error_reporting & $errno) )
        return;
    

    Also take a look at the log_errors and error_log options, for automatically logging errors to a file or to syslog.