PHP脚本未验证输入

时间:2015-06-22 17:30:26

标签: php html contact-form

为什么此脚本无法验证电子邮件地址,姓名和电话号码?它正在发送电子邮件,但没有通知我输入字段中的故意错误。 (此脚本从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表单标记和脚本标记的内容,以显示我希望电子邮件,姓名和电话号码错误显示在这些字段的输入框的右侧,如果有错误,我希望保留Contact_Us页面。我怎么做? (还在HTML表单内容下面发布工作php脚本。)

在Head标签中:

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

在Body标签中:

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

}

?>

2 个答案:

答案 0 :(得分:1)

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

你应该将你的邮件声明包装成if 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 );
}

答案 1 :(得分:0)

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

die函数的方式是这种方法的重要关键之一。正如评论中所提到的,它会停止对文件的任何进一步处理 - 无论是简单地发出HTML还是评估php代码。

如果&#39;验证&#39; (我没有执行)失败,你会在有问题的字段旁边得到一个星号。它还会将可接受的字段返回到表单中的输入中,从而无需再次输入所有信息,只是为了在其中一个输入中出错。

将它扔到服务器上并进行游戏。关于这种方法,我有两种想法。一方面,它将所有内容联系在一起。另一方面,你最终可以在一个文件(php,html,css,js)中使用4种语言,并且可以很快变得有点呃,维护起来不愉快。

<强> 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>