我为朋友创建了一个网站,这是我的第一个网站。目前已经上传并托管了。
创建了一个基本的"与我联系"表单,用户可以填写信息,然后它将发送电子邮件。
问题是:点击提交后,如何在提交表单后将网页重定向回index.html"来自php的回复。
这是html表单部分:
<div class="contactme" id="contactme">
<form class="form-horizontal" method="post" name="myemailform" action="form-to-email.php">
<fieldset>
<h2>Let's Create Together</h2>
<hr class="small">
<div class="form-group">
<label class="col-lg-2 control-label">Name</label>
<div class="col-lg-10">
<input type="text" class="form-control" name="name" placeholder="Name">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">E-Mail</label>
<div class="col-lg-10">
<input type="email" class="form-control" name="visitor_email" placeholder="E-Mail">
</div>
</div>
<div class="form-group">
<label class="col-lg-2 control-label">Message</label>
<div class="col-lg-10">
<textarea class="form-control" rows="8" name="message"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button type="reset" class="btn btn-default">Cancel</button>
<button type="submit" name="submit" id="submitbutton" class="btn btn-primary mainButton">Submit</button>
</div>
</div>
</fieldset>
</form>
</div>
这是单独的.php代码。这是在另一个文件上。
<?php
if (!isset ($_POST ['submit']))
{
//This page should not be accessed directly. Need to submist the form.
echo "error, you need to submit the form!";
}
$name = $_POST ['name'];
$visitor_email = $_POST ['visitor_email'];
$message = $_POST ['message'];
//Validation
if(empty ($name)||empty ($visitor_email))
{
echo "Name and email are mandatory!";
exit();
}
else {
echo "Submit Successful!";
header("Location: index.html");
exit();
}
$email_from = 'info@joshkelley.video'; //<== Put your email address here
$email_subject = "New Form Submission";
$email_body = "You have received a new message from the user $name.\n".
"E-mail Address: $visitor_email\n".
"Here is the message: $message\n".
$to = "brandontetrick@gmail.com"; // <==Put your email address here
$headers = "From: $email_from \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
//done
?>
任何帮助或提示都很棒。谢谢!
答案 0 :(得分:1)
如果你输出ANYTHING甚至是之前的空格,header()函数将不起作用。但是您可以将成功消息存储到会话变量中。
首先,您必须将index.html重命名为index.php
在index.php和表单脚本(使用$ _SESSION变量的任何地方)中,将session_start()函数添加到最顶层(再次,永远不会超出任何内容):
<?php
session_start();
//....
然后改变
echo "Submit Successful!";
header("Location: index.html");
exit();
这个
$_SESSION['success_msg'] = "Submit Successful!";
header("Location: index.html");
exit();
在你的index.php中
<?php
session_start();
if(isset($_SESSION['success_msg'])) {
echo $_SESSION['success_msg'];
unset($_SESSION['success_msg']); // unset this after outputting, else it will keep showing
}