0

所以我做了一个有表单的网页,并找到了一些相对简单的代码来获取表单的内容,检查它是否有错误或不完整的部分,然后返回错误或发送它。不幸的是,它在新页面中返回错误,而不是在表单页面本身中返回,这正是我想要它做的。

HTML 表单:

    <form name="contactform" method="post" action="send_form.php">
        <table width="450px">
            <tr>
                <td valign="top">
                    <label for="first_name">First Name &#42</label>
                </td>
                <td valign="top">
                    <input type="text" name="first_name" maxlength="50" size="30">
                </td>
            </tr>
            <tr>
                <td valign="top">
                    <label for="last_name">Last Name &#42</label>
                </td>
                <td valign="top">
                    <input type="text" name="last_name" maxlength="50" size="30">
                </td>
            </tr>
            <tr>
                <td valign="top">
                    <label for="email">Email Address &#42</label>
                </td>
                <td valign="top">
                    <input type="text" name="email" maxlength="80" size="30">
                </td>
            </tr>
            <tr>
                <td valign="top">
                    <label for="telephone">Telephone Number</label>
                </td>
                <td valign="top">
                    <input type="text" name="telephone" maxlength="30" size="30">
                </td>
            </tr>
            <tr>
                <td valign="top">
                    <label for="comments">Comments &#42</label>
                </td>
                <td valign="top">
                    <textarea name="comments" maxlength="1000" cols="25" rows="6"></textarea>
                </td>
            </tr>
            <tr>
                <td colspan="2" style="text-align:center">
                    <h6>An astrisk (&#42) denotes a required field.</h6>
                    <input type="submit" value="Submit" />
                </td>
            </tr>
        </table>
    </form>

PHP代码:

if(isset($_POST['email'])) {

$email_to = "my@email.com";
$email_subject = "Comments";


function died($error) {
    //This is where I think the code that prints to the same webpage should be rather than putting on a new page, which is what I does now
    echo "There were error(s) found with the form you submitted. Please review these errors and resubmit.";
    echo "These errors appear below.<br /><br />";
    echo $error."<br /><br />";
    echo "Please go back and fix these errors.<br /><br />";
    die();
}

// validation expected data exists
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);
}
$email_message = "Form details below.\n\n";

function clean_string($string) {
  $bad = array("content-type","bcc:","to:","cc:","href");
  return str_replace($bad,"",$string);
}

$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Telephone: ".clean_string($telephone)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";


// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);  

<!-- email success html -->
<h4>Thank you for contacting us. We will be in touch with you very soon.</h4>
<h4><a class="submitSuccess" href="index.php">Return to Index</a></h4>

}

我基本上希望它在文本框上方打印一行文本,说明表单未正确填写。现在它会创建一个带有错误的新网页。

旁注:应该有一些 php 括号,但是代码没有正确显示,所以我把它们拿出来了。不过,您会了解代码的想法。

4

3 回答 3

2

查看您的代码,PHP 页面的基本行为是检查是否存在任何验证错误。如果是,则显示错误消息,否则发送电子邮件。

您要做的是显示带有验证错误的原始页面。

通常,至少在我知道的几乎每个框架中,这是通过使用重定向来完成的。基本上,如果没有错误,我们会将用户重定向到成功页面。

如果有错误,我们将错误信息+用户数据放在一个会话变量中并重定向到原始表单。

基本代码结构如下所示:

验证脚本:

if ( validate_form($_POST))
{
     /*
         Form validation succeeded, 
         Do whatever processing you want (Like sending an email)
     */    
     header('location: success.php'); // redirect to the success page
}
else
{
     /*
         Form validation failed        
     */
     session_start(); 
     $error = ...;
     $form_data = array('error' => $error, 'username' => $_POST['username'], ...);
     $SESSION['form_data'] = $form_data;
     header('location: form.php');

}

表单脚本:

<?php
     session_start(); 
     if( isset($SESSION['form_data']))
     { 
         $username = $SESSION['form_data']['username'];
         $errors = $SESSION['form_data']['error'];
     }
     else
     {
         $username = '';
         $errors = '';          
     }

?>

<form name="contactform" method="post" action="send_form.php">
      <input type="text" name="username" value=<?php $username ?> >       
      <label for="errors"><?php $errors ?></label>   
</form>

PS:这段代码是一个简单的演示,显然不是100%正确的。你必须添加更多的异常处理,更多的安全检查......但你明白了。

我建议您尝试使用轻量级 MVC 框架来了解如何以正确的方式完成此操作。您甚至可以查看这些框架的源代码。

于 2012-10-02T13:25:07.887 回答
0

通过说:

<form name="contactform" method="post" action="send_form.php">

您正在告诉 HTML 表单转到 web 浏览器中的 send_form.php。然后,在 send_form.php 中,执行逻辑以查看表单的内容是否正确,因此它会在新页面上显示回显。

您将不得不在原始 HTML 页面中使用一些脚本 (javascript/php) 来检查表单是否填写正确。

看到这样的东西:http ://www.thesitewizard.com/archive/validation.shtml

于 2012-10-02T13:16:49.267 回答
0

当您的表单数据未通过您的验证服务器端时,您调用函数 dead() 并在最后使用 die()。请检查 PHP 帮助以确保 die() 满足您的需求。Cause die 告诉 PHP 停止解析 PHP 并将页面原样发送到客户端。所以你的表格永远不会出现。

Personnaly:我使用 die 函数仅用于调试目的

于 2012-10-02T13:09:36.583 回答