Output Buffering (Get rid of "headers already sent" errors

Support, Snippets & Projects

Moderators: Moderator, Global Moderator

Post Reply
ner0
Hero Member
Hero Member
Posts: 982
Joined: Sat May 22, 2004 4:45 pm

Output Buffering (Get rid of "headers already sent" errors

Post by ner0 »

I\'m sure lots of people have had the problem before, the annoying \"Headers already sent by output....\" PHP error.

I\'ve always tried to structure code such that headers are infact the first output on a page, although occasionally its infeasible and impractical in the context of a particular design, for this reason I thought I\'d share a simple workaround, it may not be the most elegant approach, but it saves lots of time, code and possible headaches.

If you had code such as the following:
[code]<?php
echo "foo";
header("Location: http://www.google.com");
?>[/code]
this error would appear, quite rightly, as headers should be the first thing the browser receives in order to render a page correctly, if the browser receives \"foo\" first, well... we don\'t have a good situation.

Suppose that the code could not be changed around, lets say the header\'s location (in this case [url=\"http://www.google.com)\"]http://www.google.com)[/url] wasn\'t actually a string URL, but was instead influenced by a variable set throughout the execution of the script. Something like the following

[code]<?php
$url = $_GET[\'url\'];
header("Location: {$url}");
?>[/code]

I hope to god nobody ever DOES use code like this, but anyway...

This case would call for output buffering (or some other way that I\'m not familiar with, I never claim to be great at PHP <img src=\'http://www.killanet.net/forum3/public/s ... >/blum.gif\' class=\'bbc_emoticon\' alt=\':P\' />)

The following code will suppress any errors, and prioritise the information to be sent, such as the header command, which should be sent first.. will be cached at the beginning of the buffer, and will therefore be output first once the buffer is \"flushed\" if there were any echo or print statements within the code, they would follow the headers in terms of priority.

[code]<?php
ob_start();
$url = $_GET[\'url\'];
header("Location: {$url}");
ob_end_flush();
?>[/code]

Note, if you intend to use output buffering, its generally a good idea to just have all your output inside the buffer, unless you want to get complicated, in which case you can use multiple buffers, but that\'s out of the scope here!... the easiest way to accomplish output buffering is to have ob_start(); as your first line of code (obviously comments can preceed), and ob_end_flush(); as your last.

If there\'s anything wrong here, or if you need help clarifying anything, post back!

Regards
Paul
[color=\"green\"]'class KPIM::ProcessManager' only defines private constructors and has no friends[/color] <- :( poor class



[18:09:00] * ~Moppy stews ner0 erotically 1 times.
Post Reply

Return to “PHP &amp; MySQL”