如何在php表单提交后重定向到成功/失败页面


How to redirect to success / fail pages after php form submission?

我已经成功地将以下表单提交代码集成到我的站点中,并且效果非常好。但是,我想有代码重定向用户到一个页面,如果表单提交成功,如果它失败了一个不同的页面。我如何调整下面的代码来做到这一点?这真的开始让我心烦了!: - 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的用户。如何修改代码,使其仅在表单字段包含数据时显示成功页面?

添加页面重定向:

// 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");
}

邮件函数成功/失败时返回true/false。很简单:

if (mail($recipient, $subject, $formcontent, $mailheader)) {
    header('location: success.php');
} else {
    header('location: fail.php');
}

添加

header("Location: successpage.html");

放到代码的底部并删除echo "Thank you!";

去掉echo,然后使用header:

header("Location: success.php");
如果失败,重定向到error.php
header("Location: error.php");

如果您想转到表单所在的页面,但显示错误或成功消息,执行以下操作:

header("Location: original.php?status=error")

或者在适当的情况下将error更改为success,然后可以使用$_GET['status']来确定表单是否失败/成功。

与其向客户端发送重定向,导致对web服务器的另一次调用,我认为更好的方法是使用PHP include。

if (mail($recipient, $subject, $formcontent, $mailheader))
    include 'success.php';
else
    include 'fail.php';
If (failure) {标题("位置:success.php");退出;} else if (success) {回声"谢谢";}