【问题标题】:Validating data entered by the user in php验证用户在php中输入的数据
【发布时间】:2014-04-14 04:55:49
【问题描述】:

我想验证用户输入到 mysql 数据库的数据。 因此,用户不能在需要数字的字段中输入字母。 并在验证后将数据输入数据库。 我已经编写了该代码,但它不起作用.. 它接受数字字段的字母

<?php
include 'testinput.php';
error_reporting(E_ERROR | E_PARSE);

if(isset($_POST['submitted'])){
    $con = mysqli_connect("localhost","USERNAME","PASSWORD","DATABASE");
    if(mysqli_connect_errno()){
        echo "Failed to connect";
        }  

        $card1 = test_input($_POST['card']);
        $first1= $_POST['first'];
        $last1=  $_POST['last'];
        $id1 = test_input($_POST['id']);
        $mob1 = test_input($_POST['mobile']);
        $vis1 = test_input($_POST['visit']);

        $query = "INSERT INTO aftness1_clients.clients (card, first, last, id, mobile, visit) VALUES ('$card1','$first1','$last1','$id1', '$mob1','$vis1')";

        if(!mysqli_query($con, $query)){
            echo "Error ". mysqli_error($con);
            echo "<br>";
        }
        $newrecord ="<b>One client added Successfully !</b>";

}// end of main if


?>


<html>
    <header>
        <title>
            Add a Client
        </title>
    </header>
<body bgcolor="#F0FFFF">
<br/> <br/> <center><font size="5" color="#4EE2EC">  Clients Information </font> </center> <br/>
<b>All fields are required:</b> <br/> <br/>

    <form action = "insert.php" method="post">
        <input type="hidden" name="submitted" value="true"/>
        <fieldset>

            <legend>New Client</legend>
            <lable><font size="3" color="#38ACEC"><b>Card Number:</b></font></lable>   
            <input type="text" STYLE="font-family: Verdana; font-weight: bold; font-size: 12px;" size="10" maxlength="30" name="card"/><br/>
            <lable><font size="3" color="#38ACEC"><b>First Name:</b></font></lable>    
            <input type="text" STYLE="font-family: Verdana; font-weight: bold; font-size: 12px;" size="10" maxlength="30" name="first"/><br/>
            <lable><font size="3" color="#38ACEC"><b>Last Name:</b></font></lable>     
            <input type="text" STYLE="font-family: Verdana; font-weight: bold; font-size: 12px;" size="10" maxlength="30" name="last"/><br/>
            <lable><font size="3" color="#38ACEC"><b>ID Number:</b></font></lable>     
            <input type="text" STYLE="font-family: Verdana; font-weight: bold; font-size: 12px;" size="10" maxlength="30" name="id"/><br/>
            <lable><font size="3" color="#38ACEC"><b>Mobile Number:</b></font></lable> 
            <input type="text" STYLE="font-family: Verdana; font-weight: bold; font-size: 12px;" size="10" maxlength="30" name="mobile"/><br/>
            <lable><font size="3" color="#38ACEC"><b>Visits:</b></font></lable> 
            <input type="text" STYLE="font-family: Verdana; font-weight: bold; font-size: 12px;" size="10" maxlength="30" name="visit"/><br/>
        </fieldset>
        </br>
            <font color="#FFFFFF"> <input type ="Submit" name="submit" value = "Add" align="right"/></font>
    </form>
<?php
error_reporting(E_ERROR | E_PARSE);
echo $newrecord
?>
</body>
</html>

<br/><br/><br/>
<a href="index.php">Main Page</a>

这是 testinput 函数

<?php
function test_input($data)
{
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

我的代码哪里出了问题,还有其他方法可以检查数据的有效性吗?

【问题讨论】:

  • 您在哪里进行验证?您需要使用正则表达式或 is_int() 来验证数值
  • 请不要在随机输入时使用stripslashes()。它只会破坏它!

标签: php mysql validation


【解决方案1】:

检查这个进行验证 ctype_alpha 只检查字母 [A-Za-z] 或 preg_match ("/^[a-zA-Z\s]+$/",$data)。

【讨论】:

    【解决方案2】:

    您需要使用正则表达式或 php 数字检查功能来验证您的输入数据,例如 is_int()is_numeric()

    function test_input($data)
    {
      $data = trim($data);
      if(is_int($data)) {
        return $data;  
      }
      else {
        //do your stuff  may be redirect to again input page and display error msg.
      }
    }
    

    使用正则表达式:-

    if (preg_match('/^[0-9]+$/', $str)) {
      // contains only 0-9
    } else {
      // contains other stuff
    }
    

    【讨论】:

      【解决方案3】:

      这是我为这样的验证编写的一个 php 类。随意使用!

      <?php
      class filterInput {
      
          public function __construct() {
      
      
          }
      
          public function filterAllButNumbers($string) {
      
              return $this->returnedValue($string, preg_replace("[^0-9]", "", $string));
      
          }
      
          public function filterAllButLetters($string) { 
      
              return $this->returnedValue($string, preg_replace("[^A-Za-z]", "", $string));
      
          }
      
          public function filterAllButNumbersAndSpaces($string) {
      
              return $this->returnedValue($string, preg_replace("[^0-9 ]", "", $string));
      
          }
      
          public function filterAllButLettersAndSpaces($string) {
      
              return $this->returnedValue($string, preg_replace("[^A-Za-z ]", "", $string));
      
          }
      
          public function filterAllButNumbersAndLetters($string) {
      
              return $this->returnedValue($string, preg_replace("[^A-Za-z0-9]", "", $string));
      
          }
      
          public function filterAllButNumbersLettersAndSpaces($string) {
      
              return $this->returnedValue($string, preg_replace("[^A-Z a-z0-9]", "", $string));
      
          }
      
          public function filterHex($string) {
      
              return $this->returnedValue($string, preg_replace("[^A-Fa-f0-9]", "", $string));
      
          }
      
          public function filterSlashes($string) {
      
              return $this->returnedValue($string, stripSlashes($string));
      
          }
      
          public function filterTags($string) {
      
              return $this->returnedValue($string, strip_tags($string));
      
          }
      
          public function filterEmail($email) {
              if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
                  return true;
              } else {
                  return false;
              }
      
          }
      
          public function filterLength($string, $minimum, $maximum) {
      
              if(strlen($string) >= $minimum && strlen($string) <= $maximum) {
                  return true;
              } else {
                  return false;
              }
      
          }
      
          public function boolify($filteredString) {
              if(strcmp($filteredString, "true") == 0) {
                  return true;
              } else {
                  return false;
              }
      
          }
      
          private function returnedValue($string, $filteredString) {
              if (strcmp($string, $filteredString) != 0) {
                  return $filteredString;
              } else {
                  return "true";
              }
      
          }
      
      
      }
      
      
      
      
      
      ?>
      

      如果字符串符合条件,则返回真(以字符串形式)。

      【讨论】:

        【解决方案4】:

        在你的代码中做一些 Javascript 验证

        这里有一个简单的例子;

        <!DOCTYPE html>  
            <html lang="en">  
            <head>
                <title></title>
                <style type="text/css">
                    body
                    {
                        font-size: 9pt;
                        font-family: Arial;
                    }
                </style>
            </head>
            <body>
                Numeric Value: <input type="text" id="text1" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" />
                <span id="error" style="color: Red; display: none">* Input digits (0 - 9)</span>
                <script type="text/javascript">
                    var specialKeys = new Array();
                    specialKeys.push(8); //Backspace
                    function IsNumeric(e) {
                        var keyCode = e.which ? e.which : e.keyCode
                        var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
                        document.getElementById("error").style.display = ret ? "none" : "inline";
                        return ret;
                    }
                </script>
            </body>
            </html>
        

        希望对你有帮助!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-26
          • 1970-01-01
          • 2017-04-19
          • 1970-01-01
          • 2021-03-06
          相关资源
          最近更新 更多