HTML PHP重定向提交表单到同一页面,并显示错误消息

时间:2014-02-08 01:39:04

标签: php html forms

我正在创建提交联系表单。但是,如果按下提交按钮时出现错误的信息,我希望它返回到我的contact.php页面,并在正文页面的顶部添加一条错误消息,例如。 “我们非常抱歉,您提交的表单中发现了错误,这些错误如下所示: 不正确的电子邮件 不完整的姓氏“等等

我有两个文件,contact.php表单和send_form_email.php用于电子邮件处理

在我的联系人文件中,我有以下代码;

$inc = $_GET['inc'];
if($inc ==1) {
            echo "We are very sorry, but there were error(s) found with the form you submitted. ";
            echo "These errors appear below.<br /><br />";
            echo $error."<br /><br />";
            echo "Please go back and fix these errors.<br /><br />";}
    ?>

在我的send_form_email.php中,我有以下代码

function died($error) {
    header("location: contact.php?inc=1"); 
    die();
}

if(!isset($_POST['first_name']) ||
    !isset($_POST['last_name']) ||
    !isset($_POST['email']) ||
    !isset($_POST['telephone']) ||
    !isset($_POST['comments'])) {
    died('We are sorry, but there appears to be a problem with the form you submitted.');      
}

$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$comments = $_POST['comments']; // required

$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.<br />';}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.<br />';}
if(strlen($comments) < 2) {
$error_message .= 'The Comments you entered do not appear to be valid.<br />';}
if(strlen($error_message) > 0) {
died($error_message);}

但是,当我输入错误的名称时,将不会显示错误消息。

能帮助我吗?

问候,Lex

1 个答案:

答案 0 :(得分:1)

我认为您正在尝试使用$_GET。如果是这样,您可以执行以下操作:

if($_GET['inc'] ==1)