所以我试图让联系人工作,它确实有效。但每当有人点击联系页面时,它会自动发送一封空白电子邮件。怎么阻止这个?!
PHP
<?php $name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="From: $name \n Message: $message";
$recipient = "iamtomalmond@gmail.com";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!" . " -" . "<a href='index.html'> Return Home</a>";
?>
HTML
<form action="contact.php" method="POST">
<p>Name</p> <input type="text" name="name">
<p>Email</p> <input type="text" name="email">
<p>Message</p><textarea name="message" rows="6" cols="25"></textarea><br />
<input type="submit" value="Send"><input type="reset" value="Clear">
</form>
提前致谢:(
答案 0 :(得分:5)
您需要检查是否发出了POST
请求,并且只有在这种情况下才执行邮件代码:
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
// your php code (first block in your question)
}
答案 1 :(得分:1)
那是因为你在页面加载时调用了mail()
。如果您只想在提交表单时这样做(我怀疑),请在调用$_POST
之前检查您的某些mail()
变量是否存在。
if (isset($_POST['foo']))
{
//do stuff here
}
答案 2 :(得分:1)
在发送电子邮件之前,您的网页必须测试$_POST
阵列的内容:
<?php
if (!is_empty($_POST)) {
if (isset($_POST['email']) && isset($_POST['name']) && isset($_POST['message'])) {
// code to send email as in your question code snippet
} else {
// optionally display an error message
}
}
?>