My contact form is working, however it won't redirect me to my thanks page. It was working before I transferred it to a new host.
<!-- Contact PHP Stuff -->
<?php
session_start();
require_once 'libs/phpmailer/PHPMailerAutoload.php';
$errors = [];
if(isset($_POST['name'], $_POST['email'], $_POST['subject'], $_POST['message'])) {
$fields = [
'name'=> $_POST['name'],
'email'=> $_POST['email'],
'subject'=> $_POST['subject'],
'message'=> $_POST['message']
];
foreach($fields as $field => $data) {
if(empty($data)) {
$errors[] = 'The ' . $field . ' field is required';
}
}
if(!empty($fields['name'])) {
if (!preg_match("/^[a-zA-Z ]*$/",$fields['name'])) {
$errors[] = "Name can only include letters A-Z";
}
}
if(!empty($fields['email'])) {
if (!filter_var($fields['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = "Please enter a valid email address";
}
}
if(empty($errors)) {
$mail = new PHPMailer(); // create a new object
$mail->IsHTML(true);
$mail->Username = "contact@dhmltd.co.uk";
$mail->Password = "*****";
$mail->SetFrom($fields['email'], $fields['name']);
$mail->Subject = $fields['subject'];
$mail->Body = $fields['message'];
$mail->AddAddress("admin@dhmltd.co.uk");
if($mail->Send()) {
header('Location: thanks');
die();
} else {
$errors[] = "Sorry could not send message. Try again later";
}
}
} else {
$errors[] = 'Something went wrong';
}
$_SESSION['errors'] = $errors;
$_SESSION['thanks'] = $thanks;
$_SESSION['fields'] = $fields;
header('Location: contact#contact-form');
?>
The line header('Location: thanks');
was redirecting me to thanks.html with my previous host but now this isn't happening even though the message is being sent and delivered.
I found the code on a tutorial and can't remember where as it was over a year ago.
Remove everything before using header. You can't have ANY output whatsoever before using header()
if you add
error_reporting(E_ALL | E_WARNING | E_NOTICE);
ini_set('display_errors', TRUE);
to the page you'll probably see a 'headers already sent' error.
or you can use exit() which apparently fixed it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.