Page 1 of 1

Redirect Q - Warning: Cannot modify header information

Posted: Tue Jul 21, 2009 12:30 pm
by beaner_06
How would I do a redirect on a contact form after a user successfully submits the form. I tried doing a header Location:, but I received that error. Basically I don't want to display just the Success! text, I want to redirect. Here is my code:

Code: Select all

 
<?php
if(isset($_POST['submit'])) {
 
$to = "ryanbuening@gmail.com";
$subject = "ryanbuening.com Contact Form";
$firstname_field = $_POST['first'];
$lastname_field = $_POST['last'];
$email_field = $_POST['email'];
$comments = $_POST['comments'];
 
$body = " From: $firstname_field $lastname_field\n E-Mail: $email_field\n Comments: $comments";
 
echo "Success!";
header ("Location: http://www.ryanbuening.com");
mail($to, $subject, $body);
 
} else {
 
echo "blarg!";
 
}
?>
 

Re: Redirect Q - Warning: Cannot modify header information

Posted: Tue Jul 21, 2009 12:34 pm
by Christopher
You cannot echo, or send any output, before you call the header() function. Any output, even spaces between/before/after <?php ?> tags will cause PHP to send the HTTP headers. Once that happens you cannot call header() to send more headers.

Re: Redirect Q - Warning: Cannot modify header information

Posted: Tue Jul 21, 2009 1:06 pm
by spider.nick
arborint wrote:Any output, even spaces between/before/after <?php ?> tags will cause PHP ...
Actually, that is not true. You can absolutely have space between the <?php and ?>. You can have an infinite number of lines of code. Just make sure you do not output anything [i.e. - echo] to the screen. From php.net:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
source

Nick