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?
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.
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();
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With