NYCPHP Meetup

NYPHP.org

[nycphp-talk] PHP REDIRECT

David Krings ramons at gmx.net
Wed Sep 5 19:16:22 EDT 2007


PaulCheung wrote:
> Thanks David, Dan and bz
> 
> the missing quote was just a copying error. Using the header('location: 
> http://localhost/mainmenu.php');
> 
> this is the value of $number_of_records  = 0
> Warning: Cannot modify header information - headers already sent by 
> (output started at C:\xampp\htdocs\etestform.php:4) in 
> C:\xampp\htdocs\etestform.php on line 59
> 
> This is the error message the 4 at the end of 
> C:\xampp\htdocs\etestform.php:4 - points to script line 4. which is
> <script language="JavaScript" type="text/javascript">
> 
> Line 59 is
> 57      if ($b == 0)
> 58        {echo 'this is the value of $number_of_records  = ' . 
> $number_of_records;
> 59        header('location: http://localhost/mainmenu.php');}
> 60        else
> 

That explains it. Line 58 echos something, which is body content and 
then you try to modify the header, which is long gone to the client. And 
even if that would work, PHP would echo the line and immediately tell 
the browser to go somewhere else. Nobody can read that fast. You need to 
craft line 59 into a regular hyperlink and have the user click on it.

The error message does tell you what went wrong. And it also tells you 
where the offending output started, exactly at line 4. OK, I can see how 
one could find line 4 to be the cuplrit and to some extent it is. It is 
the chicken and the egg problem, is the header redirect at the wrong 
place or the output?

 > Using PseudoCode - Is there anything in PHP that will simply just sayes
 > the following
 >
 > If  $number_of_records == 0
 >    goto http://www.localhost/mainmenu.php ??

That depends, if there is no output before that, then you can use a 
header redirect. If there is output you could write it to a buffer and 
once all is settled and no redirects could potentially take place you 
blurt out the buffer. Usually, that is not necessary, but I recall that 
I used it once and forgot why, but I remember that the alternatives 
weren't that satisfying.

Hope that helps,

	David



More information about the talk mailing list