So I am using and successfully sending emails out using PHPmailer yet once the email sends I am not sure where to put the page redirect back to the page you came from with a message saying message sent perhaps?
<?php
if (isset($_POST['hp']) && $_POST['hp'] && $_POST['hp'] != '') {
}
else {
require 'c:\php\includes\PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = ''; // Specify main and backup server
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = ''; // SMTP username
$mail->Password = ''; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable encryption, 'ssl' also accepted
$mail->Port =;
$mail->From = '';
$mail->FromName = '';
foreach ($members as $user) {
$mail->addAddress($user->user_email);
}
foreach ($committee as $user) {
$mail->AddCC($user->user_email);
}
$mail->WordWrap = 50; // Set word wrap to 50 characters
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $_POST["Subject"];
$mail->Body = $_POST["contentfield"];
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
}
?>
I have taken all my details out for obvious reasons.
Why not add an else to your if()
mail doesn't send statement and redirect the user if the if statement does not fail?
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
} else {
// email sent successfully, redirect to success page
header ('Location: sent.php');
}
Your email should still send because the browser will only redirect you if $mail->send()
evaluates to true... and at this point the mail has already sent.
You could also put the redirect after the if()
statement if you wanted to and that should also work because if your if()
statement evaluates to true it will exit the script.
You can send HTTP redirects in PHP using the location header:
<?php
header('Location: /path/to/page');
exit;
You don't necessarily need to have a redirect. You could just return a 204 No Content
and the browser wil stay where it is. If you want to return a status code, you could pass the result in the redirect as a param, redirect to a different page, or stick a value in the session, ready to display on the next page. Something like:
if(!$mail->send()) {
header('Location: failed.php?error='.rawurlencode($mail->ErrorInfo));
}
header('Location: success.php');
}