【问题标题】:PHP script not validating inputPHP脚本不验证输入
【发布时间】:2015-09-08 06:36:36
【问题描述】:

为什么这个脚本不验证电子邮件地址、姓名和电话号码?它正在发送电子邮件,但没有通知我输入字段中的故意错误。 (这个脚本是从 html 表单标签中调用的)。

<?php
// define variables and set to empty values
$emailErr = $nameErr =  $phoneErr = "";
$email = $name = $phone = $message = "";

function test_input($data) {
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   if (empty($_POST["email"])) {
     $emailErr = "Email is required";
   } else {
     $email = test_input($_POST["email"]);
     // check if e-mail address is well-formed
     if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
       $emailErr = "Invalid email format";
     }
   }

   if (empty($_POST["name"])) {
     $nameErr = "Name is required";
   } else {
     $name = test_input($_POST["name"]);
     // check if name only contains letters and whitespace
     if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
       $nameErr = "Only letters and white space allowed";
     }
   }

   if (empty($_POST["phone"])) {
     $phone = "";
   } else {
     $phone = test_input($_POST["phone"]);
     // check if phone number is valid (this regular expression also allows dashes in the phone number)
     if (!preg_match("/^[0-9+'('+')'+ '-' ]*$/",$phone)) {
       $phoneErr = "Invalid Phone Number";
     }
   }

  $email = $_REQUEST['email'] ;
  $name = $_REQUEST['name'] ;
  $phone = $_REQUEST['phone'] ;
  $message = $_REQUEST['message'] ;

  mail( "omitted@omitted.com", "Contact Us Inquiry",
    $message, "From: $email" );
  header( "Location: http://omitted.com/ThankYou.html" );
}


?>

更新于 2015 年 6 月 23 日,几乎是美国东部时间午夜 表单现在验证输入,但我希望它更漂亮。

发布 HTML 表单标签和脚本标签的内容,以显示我希望电子邮件、姓名和电话号码错误出现在这些字段的输入框的右侧,如果有错误,我想留在联系我们页面。我怎么做? (还在 HTML 表单内容下方发布工作 php 脚本。)

在Head标签中:

<style>
.error {color: #00a261;}
</style>

在正文标签中:

<p><span class="error">* required field. </span></p>

<form method="post" name="contact_us_form" action="contact_us_e_mail.php">  
<div align="center">
   Email: &nbsp;<input name="email" type="text" border-style="solid" border-width="1px" style="border-color:#00a261" value=""/><span class="error">&nbsp;*&nbsp; 
   <?php 
   echo $emailErr; ?> 
   </span><br /><br />
   Name: &nbsp;<input name="name" type="text" border-style="solid" border-width="1px" style="border-color:#00a261" value=""/><span class="error">&nbsp;*&nbsp; 
   <?php echo $nameErr; ?> 
   </span><br /><br />
   Phone: &nbsp;<input name="phone" type="text" border-style="solid" border-width="1px" style="border-color:#00a261" value=""/><span class="error">&nbsp;*&nbsp; 
    <?php echo $phoneErr; ?> 
   </span><br /><br />
   Message:<br />
   <textarea name="message" border-style: solid style="border-color:#00a261" rows="15" cols="80">
   </textarea>
   <br />
    <input type="submit" value="Submit"/>
</form>

修改后的 php 脚本(称为contact_us_e_mail.php):

    <?php
// define variables and set to empty values
$emailErr = $nameErr = $phoneErr = "";
$email = $name = $phone = $message = "";

function test_input($data) {
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   if (empty($_POST["email"])) {
     $emailErr = "Email is required";
   } else {
     $email = test_input($_POST["email"]);
     // check if e-mail address is well-formed
     if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
       $emailErr = "Invalid email format. Please use browser's back button and correct.";
     }
   }

   if (empty($_POST["name"])) {
     $nameErr = "Name is required";
   } else {
     $name = test_input($_POST["name"]);
     // check if name only contains letters and whitespace
     if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
       $nameErr = "Only letters and white space allowed in Name. Please use browser's back button and correct.";
     }
   }

   if (empty($_POST["phone"])) {
     $phoneErr = "Phone is required";
   } else {
     $phone = test_input($_POST["phone"]);
     // check if phone number is valid (this regular expression also allows dashes in the phone number)
     if (!preg_match("/^[0-9+'('+')'+'-']*$/",$phone)) {
       $phoneErr = "Invalid Phone Number. Please use browser's back button and correct.";
     }
   }

  $email = $_REQUEST['email'] ;
  $name = $_REQUEST['name'] ;
  $phone = $_REQUEST['phone'] ;
  $message = $_REQUEST['message'] ;

if($nameErr == '' && $phoneErr == '' && $emailErr == ''){
  mail( "omitted@omitted.com", "Contact Us Inquiry",
    $message, "From: $email" );
   header( "Location: http://omitted.com/ThankYou.html" );
}else{
   echo $emailErr, "<br />"; 
   echo $nameErr, "<br />";  
   echo $phoneErr, "<br />";    
   //$errorList = $nameErr . ' ' . $phoneErr . ' ' . $emailErr;
   //header( "Location: http://omitted.com/Contact_Us.html" );
}

}

?>

【问题讨论】:

  • 你能定义prettier吗?我希望你能理解,这完全是主观的。 :) 期望的输出是什么?
  • 我希望错误显示在 HTML Contact_Us.html 页面上,分别位于电子邮件、姓名和电话字段的输入框右侧。
  • 啊哈。明白了。好吧,在那种情况下 - 我会让表单存在于一个 php 文件中。然后我会将表单提交回同一个 php 文件。如果所有输入都验证正常,我将继续执行实际的电子邮件发送.但是,如果某些/所有字段未验证,那么您已经可以访问表单提交的 POST 变量。然后,您可以使用这些来填充您在输出表单时拥有的 .error 跨度(第二次或后续时间)。这有帮助吗?
  • 不知道我可以将表单放入 PHP 文件中。和上面一样吗?
  • 是的,当然可以!没有仔细查看您的代码。我只是整理了一个非常粗略的基本示例。可以通过多种不同的方式发出 html,这并不重要,也不是重点。关键是文件的循环性质,它向自己提交自己的表单。我将其发布为解决方案。 :)

标签: php html contact-form


【解决方案1】:

您正在设置变量$nameErr, $phoneErr, $emailErr,但您从不测试它们。

你应该像这样将你的邮件声明包装在一个 if 中:

if($nameErr == '' && $phoneErr == '' && $emailErr == ''){
  mail( "omitted@omitted.com", "Contact Us Inquiry", $message, "From: $email" );
  header( "Location: http://omitted.com/ThankYou.html" );
}else{
   $errorList = $nameErr . ' ' . $phoneErr . ' ' . $emailErr;
   header( "Location: http://omitted.com/errors.php?errorList=" . $errorList );
}

【讨论】:

    【解决方案2】:

    这是破解特定问题的一种方法。关键是在决定向用户呈现什么之前,在脚本的开头检查表单的变量是否存在。另一种选择是使用FormData 对象和AJAX 提交表单。您可以返回一个 JSON 对象,然后在客户端使用 JS 来决定是否隐藏/显示错误消息并在成功后重定向到另一个页面(如果需要)。

    die 的作用方式是这种方法的重要关键之一。如 cmets 中所述,它会停止对文件的任何进一步处理——无论是简单地发出 html 还是评估 php 代码。

    如果“验证”(我不执行)失败,您会在有问题的字段旁边看到一个星号。它还会将可接受的字段返回到表单中的输入中,从而避免为了仅在其中一个输入中出现错误而再次输入所有信息。

    只要把它扔到服务器上玩一玩。我对这种方法有两种看法。一方面,它将所有东西都连接在一个位置。另一方面,您最终可能会在一个文件中包含 4 种语言(php、html、css、js),而且这些语言很快就会变得有点糟糕,难以维护。

    test.php

    <?php
    /*
        sample that contains a form that will sumbit to itself
    */
        // nothing entered in the POST array - this means the page has been loaded as a result of a request originating
        // somewhere _other_ than the form in this page.
        // we'll need to display the page ready for a 'first-visit'
        if (count($_POST) == 0)
        {
            //echo ('$_POST array is empty!<br>');
            $username = $email = $message = '';
        }
    
        // no validation here, I'm assuming all are okay. You need to validate for yourself in this block of code.
        // you'll notice that submitting an empty form gives us 3 vars in the POST array, all of which are empty strings
        else
        {
            $username = $email = $message = '';
            if (isset($_POST['username']) == true)
                $username = $_POST['username'];
    
            if (isset($_POST['email']) == true)
                $email = $_POST['email'];
    
            if (isset($_POST['message']) == true)
                $message = $_POST['message'];
    
            // use this block or the 7 lines above - they have the same effect.
            /*
            $username = isset($_POST['username']) == true ? $_POST['username'] : "";
            $email = isset($_POST['email']) == true ? $_POST['email'] : "";
            $message = isset($_POST['message']) == true ? $_POST['message'] : "";
            */
    
            if ( strlen($username) == 0)
                $usernameNotPresent = true;
    
            if ( strlen($email) == 0)
                $emailNotPresent = true;
    
            if ( strlen($message) == 0)
                $messageNotPresent = true;
    
            if (( isset($usernameNotPresent)==false) && (isset($emailNotPresent)==false) && (isset($messageNotPresent) == false))
            {
                doSendMail();
    
                // execution/parsing of the file will stop here. This has 2 effects.
                // 1. Any further php code wont be interpreted and then run
                // 2. Any html that follows a call to die wont be shown.
    
                // Therefore, if we get here that means we've sent the email and there's no use in showing the
                // email form.
                // provided nothing has been output yet, you could also re-direct to another page with a call
                // to the function header
                die;
            }
        }
    
    function doSendMail()
    {
        // ToDo:
        //      send the email here
    
    
    
        // print a message telling the user of the outcome of trying to send the email.
        echo "<p>Email successfully sent, please check your inbox</p>";
    }
    
    ?>
    <!doctype html>
    <html>
    <head>
    <script>
    </script>
    <style>
    .wrapper
    {
        display: inline-block;
    }
    #myForm
    {
        text-align: center;
    }
    #myForm > input, #myForm > textarea
    {
        /* display: block; */
        margin-bottom: 16px;
        width: 170px;
        text-align: left;
    }
    #myForm > input[type='submit']
    {
        width: 50%;
        text-align: center;
    }
    </style>
    </head>
    <body>
        <div class='wrapper'>
            <form id='myForm' method='post' action='' >     <!-- an empty action attribute submits the form back to itself -->
                <?php
                    if (isset($usernameNotPresent))
                        echo "<input type='text' name='username' placeholder='enter username'><span class='error'>*</span></br>";
                    else
                        echo "<input type='text' name='username' placeholder='enter username' value='$username'></br>";
                ?>
                <?php
                    if (isset($emailNotPresent))
                        echo "<input type='text' name='email' placeholder='enter email address'><span class='error'>*</span></br>";
                    else
                        echo "<input type='text' name='email' placeholder='enter email address' value='$email'></br>";
                ?>
                <?php
                    if (isset($messageNotPresent))
                        echo "<textarea name='message' placeholder='enter your message'></textarea><span class='error'>*</span></br>";
                    else
                        echo "<textarea name='message' placeholder='enter your message'>$message</textarea></br>";
                ?>
                <div><input type='submit' value='GO'/></div>
            </form>
        </div>
    </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-23
      • 1970-01-01
      • 2016-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多