phperror-reportingob-get-contents

allow ob_get_contents and to grab warnings but not display them in front end


I have a script developed in PHP7.2 running on a CentOS machine and I've been struggling to get ob_get_contents to work.

In the php.ini file, I have set display_errors to Off and error_reporting to this:

error_reporting = E_ALL & ~E_NOTICE

Here's the code that gets executed:

    ob_start();
    $result = $db->query($query); //This executes a query
    $report_error = ob_get_contents();
    if (!$result)
                {
                    log_error("Query Failed: ".$report_error);
                    return false;
                }

   ob_end_flush();
   ob_start();

Setting display errors to On works but I don't want to display errors in the front end to the user, that's not something we would want in production so not sure if there's another setting in the php.ini file I need to change to capture warnings but not show them in the frontend?

Thanks


Solution

  • You want display_errors = On and then selectively report errors when you are buffering for the errors using error_reporting().

    At the start of your application you want error_reporting(0).

    Also, don't flush the buffer, that sends the output to the browser. You want to clean the buffer with ob_end_clean().

    Or get and clean in one:

    ob_start();
    error_reporting('E_ALL & ~E_NOTICE');  //report errors
    $result = $db->query($query);
    $report_error = ob_get_clean();
    error_reporting(0);                    //report NO errors
    if (!$result)
                {
                    log_error("Query Failed: ".$report_error);
                    return false;
                }
    

    However, that database class probably implements a way to retrieve errors without having to go through this.