Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ob_start gets interrupted when error occur

Tags:

php

buffer

So ob_start() is supposed to capture output until another buffer function is called like ob_get_clean(), ob_get_contents(), ob_get_flush().

But when an exception is thrown inside the buffer reader it will effect the reader by stopping it and echo the output instead of keep capturing it. This is what I want to prevent.

Lets say this is my script:

<?php
    error_reporting(0);
    try {
        ob_start();
            echo "I don't wanna output this what so ever, so want to cache it in a variable with using ob_ functions";
            $unlink = unlink('some file that does not exist');
            if(!$unlink) throw new Exception('Something really bad happen.', E_ERROR); //throwing this exception will effect the buffer
        $output = ob_get_clean();
    } catch(Exception $e) {
        echo "<br />Some error occured: " . $e->getMessage();
        //print_r($e);
    }
?>

This script will output:

I don't wanna output this what so ever, so want to cache it in a variable with using ob_ functions
Some error occurred: Something really bad happen.

When it's suppose to just print

Some error occurred: Something really bad happen.

What am I doing wrong, is there a solution?

like image 354
Junior Avatar asked Jul 14 '13 04:07

Junior


2 Answers

My guess is that even inside your catch block, output buffering is still active. However, the script ends with active output buffering, so PHP automatically shows the output buffer.

So you can try to call ob_clean() inside your exception handler.

like image 187
Shi Avatar answered Nov 12 '22 17:11

Shi


You can do something like this:

<?php
    error_reporting(0);
    $currentBuffers = '';
    try {
        ob_start();
        echo "I don't wanna output this what so ever, so want to cache it in a variable with using ob_ functions";
        $unlink = unlink('some file that does not exist');
        if(!$unlink) throw new Exception('Something really bad happen.', E_ERROR); //throwing this exception will effect the buffer
        $output = ob_get_clean();
    } catch(Exception $e) {
        $currentBuffers = ob_get_clean();
        ob_end_clean(); // Let's end and clear ob...
        echo "<br />Some error occured: " . $e->getMessage();
        //print_r($e);
    }

    // Do something to $currentBuffer

    // Maybe start again?
    ob_start();
    echo "foo";
    $currentBuffers .= ob_get_clean();
    //echo $currentBuffers;
        ob_end_clean();
?>
like image 41
Rainulf Avatar answered Nov 12 '22 18:11

Rainulf