PHP Typical usage and reasons for using ob_start


Example

ob_start is especially handy when you have redirections on your page. For example, the following code won't work:

Hello!
<?php
  header("Location: somepage.php");
?>

The error that will be given is something like: headers already sent by <xxx> on line <xxx>.

In order to fix this problem, you would write something like this at the start of your page:

<?php
  ob_start();
?>

And something like this at the end of your page:

<?php
  ob_end_flush();
?>

This stores all generated content into an output buffer, and displays it in one go. Hence, if you have any redirection calls on your page, those will trigger before any data is sent, removing the possibility of a headers already sent error occurring.