PHP和联系表格 [英] PHP and contact form
问题描述
我无法为我的联系表单获取正确的PHP脚本。我设法给它发电子邮件,但它没有在电子邮件中显示姓名,电子邮件或文本。
I'm having trouble getting the php script correct for my contact form. I managed to have it email me but it doesn't show a name, email or text in the email.
PHP脚本
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = 'myemail@email.comm';
$subject = 'Hello';
mail ($to, $subject, $message, "From: " . $name);
echo "Your Message has been sent.";
?>
联系表格
<form role="form" action="contact.php">
<div class="form-group">
<label for="InputName">Name</label>
<input name="name" type="text" class="form-control" id="InputName" placeholder="Enter Name">
</div>
<div class="form-group">
<label for="InputEmail">Email Address</label>
<input name="email" type="email" class="form-control" id="inputEmail" placeholder="Enter email">
</div>
<div class="form-group">
<label for="InputText">Message</label>
<input name="message" type="text" class="form-control" id="InputText" placeholder="Enter Text">
</div>
<button name="submit" type="submit" class="btn btn-default">Send</button>
</form>
推荐答案
你正在使用POST变量,但你的表格是以下内容:
You're using POST variables, yet your form being the following:
<form role="form" action="contact.php">
没有定义POST方法。如果未定义方法,则表单默认为GET。
doesn't have a POST method defined. Form defaults to GET when a method isn't defined.
因此,您需要将表单更改为
Therefore, you will need to change your form to
<form role="form" action="contact.php" method="post">
根据你留下的评论:
From a comment you left:
我仍然遇到一个问题,而不是给我输入他们输入的电子邮件,它给出了托管公司创建的电子邮件,这是不好的。
A:这很可能是因为你如何使用来自:
in你的代码,这个人的名字。邮件正在等待电子邮件地址。
A: It's most likely because of how you're using From:
in your code, which is the person's name. Mail is expecting an Email address.
替换:
mail ($to, $subject, $message, "From: " . $name);
with:
mail ($to, $subject, $message, $header);
并在 $ subject ='Hello'下添加以下内容;
$header = "From: ". $name . " <" . $email . ">\r\n";
这样,您将在电子邮件中看到此人的姓名,同时拥有有效的发件人标题。
That way, you will see the person's name in the Email, while having a valid "From" header.
- 访问 http://php.net/manual/en/function.mail.php ,了解有关邮件标题的更多信息。
附加说明:
我还建议您测试是否有任何使用以下字段不会留空:
I also suggest that you test if any of the fields aren't left empty using:
if(!empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['message']))
{
// execute code
}
否则,任何人都可以发送没有任何信息的电子邮件。
Otherwise, anyone could send an Email without any information at all.
您还可以添加 else {}
,如 else {echo请填写所有字段。; }
- 这是一个非常基本的方法。
这篇关于PHP和联系表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!