PHP Output Buffering Typical usage and reasons for using ob_start

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!


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

  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:


And something like this at the end of your page:


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.

Got any PHP Question?