PHP form: Cannot modify header information - heade

2019-09-18 16:09发布

This question already has an answer here:

I know that this question has been asked many times, however, I can't seem to find solutions that are relevant to my situation, since they mostly deal with wordpress.

Here is my mail form:

 <?php 
 $to = "email@gmail.com" ; 
 $from = $_REQUEST['email'] ; 
 $name = $_REQUEST['name'] ; 
 $headers = "From: $from"; 
 $subject = "Contact Submission From domain.com"; 

 $fields = array(); 
 $fields{"name"} = "name"; 
 $fields{"title"} = "title"; 
 $fields{"email"} = "email"; 
 $fields{"phone"} = "phone"; 
 $fields{"prefer_phone"} = "pref_phone"; 
 $fields{"prefer_email"} = "pref_email";
 $fields{"message"} = "message";
 $fields{"referral"} = "referral"; 

 $body = "Here is their submitted message:\n\n"; foreach($fields as $a => $b){  $body .= sprintf("%20s: %s\n\n",$b,$_REQUEST[$a]); } 

 if($from == '') {print "You have not entered an email, please hit back and resubmit";} 
 else { 
 $send = mail($to, $subject, $body, $headers);

 if($send) 
 {header( "Location: http://www.domain.com/sent.html" );} 
 else 
 {print "We encountered an error sending your mail, please notify support@domain.com";} 
 }
 ?>

The email sends just fine, but I get the titular error for the redirect:

Warning: Cannot modify header information - headers already sent by (output started at /home/wills5/public_html/send_henry.php:1) in /home/wills5/public_html/send_email.php on line 23

Edit: It was frickin' whitespace before line 1 apparently, thanks guys.

If the message says the error is in line 1, then it is typically leading whitespace, text >or HTML before the opening

1条回答
forever°为你锁心
2楼-- · 2019-09-18 16:51

Chances are you have whitespace besides or above your <?php tag, or HTML or some other type of "output". Maybe even a byte order mark.

<?php

echo "Correct";
// or vvv, but not with echo
// header("Location: http://www.example.com/");

?>

(space)
(space) <?php

echo "Incorrect";
header("Location: http://www.example.com/");

?>

<div align="center">Text</div>
<?php

echo "Incorrect";
header("Location: http://www.example.com/");

?>

Footnote: As per Gavin's suggestion, and I quote: "It is good form to leave off the closing php tag on class files for this reason. It prevents the inadvertent inclusion of white-space after an included file."


查看更多
登录 后发表回答