How to clear previously echoed items in PHP

edt picture edt · Jun 29, 2009 · Viewed 92.4k times · Source

In php, is there any way to clear/remove all previously echoed or printed items?

For example:

<?php

echo 'a';
print 'b';

// some statement that removes all printed/echoed items

echo 'c';

// the final output should be equal to 'c', not 'abc'

?>

My script uses the include function. The included files are not supposed to echo anything. Just in case someone (ex = hacker) tries, I need a way to remove.

Answer

Matthew Scharley picture Matthew Scharley · Jun 29, 2009
<?php

ob_start();
echo 'a';
print 'b';

// some statement that removes all printed/echoed items
ob_end_clean();

echo 'c';

// the final output is equal to 'c', not 'abc'

?>

Output buffering functions

The output buffering functions are also useful in hackery to coerce functions that only print to return strings, ie.

<?php
ob_start();
var_dump($myVar);
$data = ob_get_clean();
// do whatever with $data
?>