假设您有一个类似于以下带有命名字段的表单:(输入字段必须命名)。
<!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>
由于 . 末尾的点,这条线会给你带来问题$message
。
$email_body = "You have received a new message from $name.\n".
"\n\n $message".
点应该是分号;
,例如:
$email_body = "You have received a new message from $name.\n".
"\n\n $message";
在测试中,我输入的消息直到更改为分号才通过。
该行echo "error; you need to submit the form!";
应该是一个die()
指令,以便停止执行。
如:die("Error. You need to submit the form.");
or you can use exit;
under yourecho
还。
如:
echo "error; you need to submit the form!";
exit;
PHP (handler.php)
使用上面显示的表格进行测试和工作。
<?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
}
?>