Forum Moderators: coopster

Message Too Old, No Replies

"Cannot modify header information" again

Can the Doctype declaration be the cause?

         

radioattic

1:25 pm on Jun 8, 2010 (gmt 0)

10+ Year Member



I have seen this in several forums before, and "think" I know the cause, but this doesn't make sense.

If I remove the Doctype declaration from a page, I don't get the error.

This page (http://example.com/test.htm) gives me the "cannot modify header" error. Code follows:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<?php
$sellerId = 111;
$numRows = 0;
if ($numRows == 0) {
if ($sellerId == 102) {
header("Location: http://example1.com/fleamarket.php");
} else {
header("Location: http://example.com/notfound.html");
}
}
?>


But if I remove the Doctype declaration, I redirect the way it's intended.
See this page (http://example.com/test_no_doctype.htm). Code follows:
<?php
$sellerId = 111;
$numRows = 0;
if ($numRows == 0) {
if ($sellerId == 102) {
header("Location: http://example1.com/fleamarket.php");
} else {
header("Location: http://example.com/notfound.html");
}
}
?>


All I have done is remove the Doctype declaration.

I'm editing this right in File Manager, so I don't think I'm adding any whitespace.

Can anyone help me with this one? THANK YOU in advance!

Steve Adams

[edited by: jatar_k at 1:41 pm (utc) on Jun 8, 2010]
[edit reason] no personal urls thanks [/edit]

brotherhood of LAN

1:31 pm on Jun 8, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Welcome to the forums radioattic,

Yes it's the doctype. You are adding HTTP headers after PHP has outputted your doctype, hence the error.

Put it below your conditional statement.

Also, typically when I am adding redirects using header(), I put "exit(0);" after it, since for the most part no further processing or output is required, just the redirect.

radioattic

2:19 pm on Jun 8, 2010 (gmt 0)

10+ Year Member



That did it; thank you! I got the strong impression that the Doctype declaration had to be the first line of the page. But I guess that's not necessary as long as all the output is after the declaration.

Matthew1980

2:54 pm on Jun 8, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi all,

The Doctype sits at the top of the area that you intend to start any html output, this can even be inside a function; cases in a switch or clauses in an if/else chain etc. So you do need to be careful sometimes where you start output to the browser & where you use the header function.

And as BrotherhoodofLAN states, placing an exit; directly after a header() is considered good practise, as it potentially stops anything further downstream from being actioned.

And yes: radioAttic Welcome to the forum ;)

Cheers,
MRb