我已成功将以下表单提交代码集成到我的网站中,效果很好。但是,如果表单提交成功,我希望代码将用户重定向到一个页面,如果失败,我希望将用户重定向到另一个页面。我怎样才能调整以下代码来做到这一点?它真的开始让我紧张了! :-P
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$enquiry = $_POST['enquiry'];
$formcontent=" From: $name \n Phone: $phone \n Message: $enquiry";
$recipient = "email@email.co.uk";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!";
?>
编辑:
好的我已将代码更改为:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$enquiry = $_POST['enquiry'];
$formcontent=" From: $name \n Phone: $phone \n Message: $enquiry";
$recipient = "email@email.co.uk";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
if(mail($recipient, $subject, $formcontent, $mailheader)){
header("Location: mailer-success.htm");
}else{
header("Location: mailer-fail.htm");
}
exit;
?>
这可行,但它永远不会进入失败页面。我猜这是因为即使字段为空,也始终会发送电子邮件。我已经进行了jquery验证(我已将其禁用以进行测试),但这显然仅适用于启用了javascript的用户。如果表单字段包含数据,我怎么能改变代码只显示成功页面?任何帮助表示赞赏。
答案 0 :(得分:6)
向页面添加重定向:
// Test to see if variables are empty:
if(!empty($name) && !empty($email) && !empty($phone) && !empty($enquiry)){
// Test to see if the mail sends successfully:
if(mail($recipient, $subject, $formcontent, $mailheader)){
header("Location: success.php");
}else{
header("Location: error.php");
}
}else{
header("Location: back_to_form.php");
}
答案 1 :(得分:3)
mail函数返回true / false。所以它很简单:
if (mail($recipient, $subject, $formcontent, $mailheader)) {
header('location: success.php');
} else {
header('location: fail.php');
}
答案 2 :(得分:2)
添加
header("Location: successpage.html");
到代码底部并删除echo "Thank you!";
答案 3 :(得分:1)
摆脱回声然后使用标题:
header("Location: success.php");
如果失败,请重定向到error.php
header("Location: error.php");
如果您要转到表单已打开的页面,但显示错误或成功消息,请执行以下操作:
header("Location: original.php?status=error")
如果合适,可以将错误更改为成功,然后您可以使用$_GET['status']
来确定表单是否失败/成功。
答案 4 :(得分:1)
与其向客户端发送重定向,导致再次调用您的Web服务器,我相信更好的方法是使用PHP包含。
if (mail($recipient, $subject, $formcontent, $mailheader))
include 'success.php';
else
include 'fail.php';
答案 5 :(得分:0)
if (failure) { header("Location: success.php"); exit; } else if (success) { echo "thank you"; }