This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
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
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."
Related
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 7 days ago.
Currently trying to create an email contact form for a personal website. The header() redirect function is not working and keeps returning the error message:
"PHP Warning: Cannot modify header information - headers already sent
by (output started at /home1/claireel/public_html/email.php:1) in
/home1/claireel/public_html/email.php on line 38"
Also, the form will send email to the testing email that I had originally had in the file but when I changed the address to the one I actually intend to use, it won't send.
<?php
$errors = [];
$errorMessage = '';
if (!empty($_POST)) {
$first = $_POST['first'];
$last = $_POST['last'];
$email = $_POST['email'];
$message = $_POST['message'];
if (empty($first)) {
$errors[] = 'First name is empty';
}
if (empty($last)) {
$errors[] = 'Last name is empty';
}
if (empty($email)) {
$errors[] = 'Email is empty';
} else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Email is invalid';
}
if (empty($message)) {
$errors[] = 'Message is empty';
}
if (empty($errors)) {
$toEmail = '************#gmail.com';
$emailSubject = 'New email from your contact form';
$headers = ['From' => $email, 'Reply-To' => $email, 'Content-type' => 'text/html; charset=utf-8'];
$bodyParagraphs = ["Name: {$first} {$last}", "Email: {$email}", "Message:", $message];
$body = join(PHP_EOL, $bodyParagraphs);
if (mail($toEmail, $emailSubject, $body, $headers)) {
header('Location: thank-you.html');
} else {
$errorMessage = 'Oops, something went wrong. Please try again later';
}
} else {
$allErrors = join('<br/>', $errors);
$errorMessage = "<p style='color: red;'>{$allErrors}</p>";
}
}
?>
I have made sure there is no white-space before the opening or after the closing php tags. I have also made sure the file is encoded in UTF-8 wihtout BOM. I also don't see anything in the file that would be outputting before the header function.
Put exit in
if (mail($toEmail, $emailSubject, $body, $headers)) {
header('Location: thank-you.html');
} else {
$errorMessage = 'Oops, something went wrong. Please try again later';
}
after header():
if (mail($toEmail, $emailSubject, $body, $headers)) {
header('Location: thank-you.html');
exit;
} else {
$errorMessage = 'Oops, something went wrong. Please try again later';
}
Following are the steps that you can take to solve your problem. This problem occurs if output buffering is not enabled with ob_start() before any output is sent to the browser, the header() function call will likely fail with an error message similar to the one you mentioned earlier ("Cannot modify header information - headers already sent..."). This is because the header() function must be called before any output is sent to the browser, including any whitespace or HTML tags.
Output buffering with ob_start() allows you to capture and manipulate any output before it is sent to the browser, which can be useful for scenarios like this where you need to ensure that the header() function is called before any output is sent.
how you can modify your code to use output buffering with ob_start() to fix the header error:
Place the ob_start() function at the very beginning of your PHP file, before any output is sent to the browser. This will enable output buffering for the entire script, capturing any output before it is sent to the browser.
Then, replace the header('Location: thank-you.html') line with ob_end_clean(); followed by header('Location: thank-you.html');. This will discard any output that was captured by the output buffer and send the header() function call with a clean output buffer.
Here's the modified code:
<?php
ob_start();
$errors = [];
$errorMessage = '';
// Rest of your code
if (empty($errors)) {
$toEmail = '************#gmail.com';
$emailSubject = 'New email from your contact form';
$headers = ['From' => $email, 'Reply-To' => $email, 'Content-type' => 'text/html; charset=utf-8'];
$bodyParagraphs = ["Name: {$first} {$last}", "Email: {$email}", "Message:", $message];
$body = join(PHP_EOL, $bodyParagraphs);
if (mail($toEmail, $emailSubject, $body, $headers)) {
ob_end_clean();
header('Location: thank-you.html');
exit; // Always exit after a header redirect
} else {
$errorMessage = 'Oops, something went wrong. Please try again later';
}
}
// Rest of your code
ob_end_flush();
?>
With this modification, any output that is generated before the header() function call will be captured by the output buffer and discarded with ob_end_clean() before the header() function is called. This should fix the "Cannot modify header information" error.
If the problem continues you can use JavaScript to redirect the page by simply echoing:
<?php
echo '<script>window.location.href = "page.php";</script>';
?>
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 6 years ago.
I am having trouble with sending emails through PHP.
So I have a form which submits to a PHP script which sends an email:
<?php
$to = "myemail#email.com";
$subject = "[Contact Form]";
$name = $_POST["name"];
$contactNumber = $_POST["contactNumber"];
$email = $_POST["email"] ;
$message = $_POST["message"];
$body = "Someone has sent a new message from the contact form. \n \n Message from: " . $name . "\n Contact Number: ". $contactNumber ."\n Email: ". $email ."\n \n Message: ". $message;
if (mail($to, $subject, $body)) {
echo ("<p>Email successfully sent!</p>");
} else {
echo ("<p>Email delivery failed…</p>");
}
?>
And the email is sent fine when for example the message is one line such as:
"Hi there how is it going?"
And fine if it is multiple lines such as
"Hi there
how is it going?"
But when I try and type a message with a comma such as
Hello there,
how is it going?
It fails?
Is there a way I can just treat the whole thing as a string possibly? Would this also fail on any other characters or is this issue just because of the way I am writing the PHP script?
This might be an obvious fix but I am new to PHP so apologies! I have tried looking around for an answer but nothing seems to fix what I am looking for.
Thanks for any help!
Try using headers in your mail function, like this:
$headers = 'MIME-Version: 1.0\r\n';
$headers .= 'Content-type: text/html; charset=UTF-8\r\n';
mail($to, $subject, $body, $headers)
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 8 years ago.
The form is submitting and sending the email successfully, but the page not redirecting to google. What am I doing wrong?
<?php
$to = "test#gmail.com";
$email_title = "test from email";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = ($_POST["name"]);
$email = ($_POST["email"]);
$message = ($_POST["message"]);
$info = " Name: $name \r\n Email: $email";
if(mail($to, $email_title, $message, $info)){
header('Location: http://www.google.com/');
}
else {
echo "there is an error";
}
}
?>
Without knowing more (for example, what the actual error looks like or what actually happens in the browser), I can only speculate. Headers can only be sent before any data is sent to the browser. My best guess is something somewhere is sending data down to the browser before the header() call, which therefore negates the header redirect.
This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 8 years ago.
I'm trying redirect users to a thank you page after submitting a form but my header location doesn't seem to work (local or online). Nothing happens when clicking the submit button (the email is sent though).
My php looks like this :
<?php
$val= $_POST['val'];
$toemail='mail#mail.com';
$name = $val['name'];
$societe = $val['societe'];
$email = $val['email'];
$phone = $val['phone'];
$msg = $val['msg'];
$subject = 'Contact';
$headers = "From: $email \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=utf-8\r\n";
$message = "<b>Nom : </b>".$name."<br>";
$message .='<b>Societe : </b>'.$societe."<br>";
$message .='<b>Email : </b>'.$email."<br>";
$message .='<b>Telephone : </b>'.$phone."<br>";
$message .='<b>Message : </b>'.$msg;
mail($toemail, $subject, $message, $headers);
header("Location: http://example.com/thankyou.html");
?>
What am I doing wrong? Thanks in advance for your help.
Edit: Thanks for your help. If I turn error reporting I get:
Warning : Cannot modify header information - headers already sent by (output started at /path/email.php:12)
As others have mentioned, the script is sending output before attempting to send the header.
The simplest way to fix it is probably to buffer the output of email() and then send the header, as follows:
ob_start();
mail($toemail, $subject, $message, $headers);
ob_end_clean();
header("Location: http://example.com/thankyou.html");
Problem is, you are sending output before redirect.
Either use output buffering or do it on a new page.
http://ee1.php.net/manual/en/ref.outcontrol.php
very simple use following method
ob_start();
exit(header("Location: http://example.com/thankyou.html"));
Functions that send/modify HTTP headers must be invoked before any output is made. Otherwise the call fails.
Using header() you can redirect only to a page within the same site.
you can try using
header("Location: /thankyou.html");
Hope it helps.
I have a header location problem despite following all the advice I can find online. The mailer script sends the email(s) but I get a 'headers already sent' error relating to Line 29 which is {header("Location: $thanksURL");} and no redirect to the confirmation page. If I replace the header location code with an instruction to print a confirmatory message instead, it works, so there must be something about the header location code that the server doesn't like.
Here is the code:
<?php
ob_start();
$to = "msheath#btinternet.com" ;
$from = $_REQUEST['email'] ;
$name = $_REQUEST['name'] ;
$headers = "From: $from";
$subject = "Request for Library Document";
$thanksURL = "http://www.postalhistory.org.uk/newsite/php/thankyou.php"; //confirmation page
$fields = array();
$fields{"name"} = "Name";
$fields{"address"} = "Address";
$fields{"email"} = "Email";
$fields{"tel"} = "Telephone No";
$fields{"author1"} = "First Author";
$fields{"title1"} = "First Title";
$fields{"author2"} = "Second Author";
$fields{"title2"} = "Second Title";
$body = "I would like to borrow the undermentioned book(s) from the PHS Library:\n\n"; foreach($fields as $a => $b){ $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }
$headers2 = "From: The Librarian, Postal History Society";
$subject2 = "Thank you for contacting the Postal History Society";
$autoreply = "Thank you for your request. Somebody will get back to you as soon as possible, usually within 48 hours.";
if($from == '') {print "You have not entered an email, please go back and try again";}
else {
if($name == '') {print "You have not entered a name, please go back and try again";}
else {
$send = mail($to, $subject, $body, $headers);
$send2 = mail($from, $subject2, $autoreply, $headers2);
if($send)
{header("Location: $thanksURL");}
else
{print "We encountered an error sending your mail, please notify webmaster#YourCompany.com"; }
}
}
ob_end_flush()
?>
Go to http://www.postalhistory.org.uk/newsite/php/library.php to try it out for yourself.
Can anyone suggest what is wrong?
Mike
'headers already sent' means you've already sent something to the browser. This could be a whitespace somewhere. It could also be that your file is encoded in UTF-8 with BOM which means you've sent the BOM to the browser
Warning: Cannot modify header information - headers already sent by (output started at /home/users/uks52804/html/postalhistory.org.uk/newsite/php/contact.php:1) in /home/users/uks52804/html/postalhistory.org.uk/newsite/php/contact.php on line 29
This means that you have output prior to your ob_start() call. ob_start should be the first instruction of the page that is including that code.
I faced the same problem a while back and found that i was echoing something before setting the headers. I removed the echo statement and also cleared some whitespaces that removed the problem