ob_start gets interrupted when error occur

buffer, php

Solution

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.

Problem

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?

Original source