Redirect Q - Warning: Cannot modify header information

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
beaner_06
Forum Newbie
Posts: 13
Joined: Tue May 19, 2009 6:11 pm

Redirect Q - Warning: Cannot modify header information

Post 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!";
 
}
?>
 
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Redirect Q - Warning: Cannot modify header information

Post 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.
(#10850)
spider.nick
Forum Commoner
Posts: 72
Joined: Wed Jul 15, 2009 12:22 pm
Location: Overland Park, KS

Re: Redirect Q - Warning: Cannot modify header information

Post 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
Post Reply