PHP Header URL Redirect Error Workaround
Are you getting this error?
Warning: Cannot modify header information – headers already sent by…
If you have worked with PHP at all, you have probably run into the problem of having code placed in your pages to redirect to another url, this especially comes into play when writing scripts to determine if a user is logged in or not.
Example PHP Header Redirect Call:
header("Location: http://www.mindwiremedia.net");
The problem is caused when there is any output generated by the scripts above the header call, it could be as simple and frustrating as some whitespace existing in the document. I myself have struggled with the limitations with redirecting pages, especially since working with Coldfusion so many tasks are made much more flexible and functional.
Since PHP 4, you can use a work around by having the server buffer all your output until you declare to send it. This is done using ob_start() and ob_end_flush() in your script.
ob_start(); //Put your page output here header("Location: http://mindwiremedia.net"); ob_end_flush();
I have success with putting the ob_start function call at the top of the page in its own <php> tags, and then having the header and ob_end_flush() call in its own <php> tags where i need to redirect.
I hope you find this useful and thank you for reading!








You have a great blog here and it is Nice to read some well written posts that have some relevancy…keep up the good work
[Reply]
You can also utilize two the Javascript & HTML redirects together to ensure a page is redirected even if javascript is not enables.
e.g.
<script type="text/javascript"> function redirect(loc){ window.location = loc; } </javascript> <script type="text/javascript>redirect("http://www.mindwiremedia.net");</script> <meta http-equiv="REFRESH" content="0;url=http://www.mindwiremedia.net">The javascript redirect seems to act quicker to request the url compared to the HTML redirect even if set at 0. This is why it is underneath the javascript and again encase the user does not have javascript enabled.
[Reply]
hello there:
thanks a lot for this post. i am working on a cms and these headers were a headache. i had been trying a way around since yesterday (Oct. 25, 2009). i followed your directions on ob_start(() and ob_end_flush(), and my headers are not a headache anymore.
–Willie
[Reply]
@Willie, Glad to hear it Willie!
[Reply]
Thank, for this nice information.
[Reply]
Thanks – huge help – can redirect any time within a page.
[Reply]