I have this simple script I found online but it does not work. What am I missing?
<?php
if(!isset($_POST['submit']))
{
//This page should not be accessed directly. Need to submit the form.
echo "error; you need to submit the form!";
}
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];
$email_from = $visitor_email;
$email_subject = "New Message";
$email_body = "You have received a new message from $name.\n".
"\n\n $message".
$to = "myemail@domain.com";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
try{
mail($to,$email_subject,$email_body,$headers);
//done. redirect to thank-you page.
header('Location: thank-you.html');
} catch(Exception $e){
//problem, redirect to sorry page
header('Location: sorry.html');
}
?>
I am always redirected to the thank-you page but I do not get any emails. All HTML stuff are correct.
Assuming you have a form similar to the following with named fields: (input fields must be named).
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="post" action="handler.php">
Name:
<input type="text" name="name" /> <br/>
Your Email:
<input type="text" name="email" /> <br/>
Message: <br>
<textarea id="body" name="message" cols="100" rows="20"></textarea><br/>
<input type="submit" name="submit" value="Send Email" />
</body>
</html>
This line would cause you problems because of the dot at the end of $message
.
$email_body = "You have received a new message from $name.\n".
"\n\n $message".
The dot should be a semi-colon ;
such as:
$email_body = "You have received a new message from $name.\n".
"\n\n $message";
In testing, the message I typed did not come through until changed to a semi-colon.
This line echo "error; you need to submit the form!";
should be a die()
directive in order to stop executing.
Such as: die("Error. You need to submit the form.");
or you could use exit;
under your echo
also.
Such as:
echo "error; you need to submit the form!";
exit;
Tested and working on my end using the form shown above.
<?php
if(!isset($_POST['submit']))
{
//This page should not be accessed directly. Need to submit the form.
// echo "Error. You need to submit the form.";
// exit;
die("Error. You need to submit the form.");
}
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];
$email_from = $visitor_email;
$email_subject = "New Message";
$email_body = "You have received a new message from $name.\n".
"\n\n $message";
$to = "myemail@domain.com";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
try{
mail($to,$email_subject,$email_body,$headers);
//done. redirect to thank-you page.
// header('Location: thank-you.html');
echo "Success"; // My echo test
} catch(Exception $e){
//problem, redirect to sorry page
// header('Location: sorry.html');
echo "Sorry"; // My echo test
}
?>