| I have written the article because like many other PHP programmers I have came across the modify headers problem with PHP, for months I was wondering what could be causing the problem, and how can I overcome it?
No doubt you've come across this:
Warning: Cannot modify header information - headers already sent by (output started at ...) in ... on line ...
In this article I aim to give you a better understanding of what the problem is, what causes it and how to solve it. As annoying as it is, it is quite easy to overcome. You may be using headers to redirect your visitors to other pages, so let me give you an example of when headers couldn't be used
<html>
<head>
<body>
<?php
$a = 1;
if($a == 1){
header("location: index.php");
}else{
echo("Not 1!");
}
?>
...
Now let me explain the reason you couldn't use headers in this situation and the cause of the problem.
header() is used to send a raw HTTP header you can find out more about HTTP headers here
It is essential that the header is defined before any output is sent to the browser either in the HTML document or with PHP, this is because once any HTML or text has been output to the browser, the browser assumes that you are happy with the headers so continues to load the page, so if you tried to change the headers you are confronted with this error message.
A very common cause of this is to read code with require() or include() where the contents of the file you are including outputs spaces or empty lines.
How to overcome it...
The bad news is there is no other way to redirect with PHP, but the good news is, there is ways around it. There are 3 solutions I have came across, some better than others:
1) Output a whole document - Instead of outputting just the small piece of HTML, output the whole document, simple! A problem with this though is file space, and if your document is big, it could use too much valuable server space. Unlike the other solutions, this is not redirecting your visitors, instead its just making sure that there is no output before you define a header
2) Output javascript redirect - This seems like the best option, but it's not, and I would avoid it, especially if you expect a large number of visitors to your website and the redirection is crucial, because the chances are a few of your visitors may have javascript disabled
3) Output META tags - This is the easiest option, by outputting just one line of HTML your browser will redirect you, and META tags cannot be disabled
So which is the best option? Personally I think it depends on the amount of HTML you wish to output, using PHP to output 1000 lines of code is impracticle but for just 20 lines of code it seems like a good option, but in my opinion the best option is to output META tags and heres how you can do that:
<META http-equiv="refresh" content="0;URL=http://www.yournewpage.com">
So there you go, I hope i've cleared up a bit of confusion about PHP header() |