我如何使用自定义函数来验证post数据在php


How can i use custom function to validate post data in php

我想使用函数验证我的表单帖子,然后将其插入数据库。我已经能够做到这一点,而不把它放入函数,但当我把它放入一个函数,它插入没有验证输入字段。谢谢,)下面是我的代码:

  <?php
      function validate_post(){
          global $link;
          if (isset($_POST['submit'])) {           
              $error = array();
              if (!isset($_POST['cat_title']) || empty($_POST['cat_title'])) {
                  $error[] = "field cannot be empty";
              } else {
                  //check if a name only contains letters and whitespace
                  if (!preg_match("/^[a-zA-Z]*$/", $_POST['cat_title'])) {
                      $cat_err = "Only letters and whitespace allowed";
                  }
              }
              //if no errors found
              if (empty($error) && empty($cat_err)) {
                  $cat_title = htmlentities($_POST['cat_title']);
                  $sql = "INSERT INTO categories(cat_title)VALUES('$cat_title')";
                  $insert = mysqli_query($link, $sql);
                  confirm_query($insert);
                  if (mysqli_affected_rows($link) == 1) {
                      $post_info = "Category has been added";
                      redirect("categories.php");
                  } else {
                      $post_info = "Adding category failed";
                  }
              } else {
                  $post_info = "Field cannot be empty";
              }
          }    
      }
  ?>
<?php validate_post(); ?><!-- call validate_post function-->
<!-- ADD CATEGORY FORM -->
<form action="" method="post">
<?php  
    if(isset($post_info))echo $post_info."<br>";
    if(isset($cat_err))echo $cat_err."'n" ?>
    <div class="form-group">
        <label for="cat_tile">Categories</label>
        <input type="text" class="form-control" name="cat_title" id="cat_tile"/>
    </div>
    <div class="form-group">
        <input type="submit" class="btn btn-primary" value="+ Add Category" name="submit" >
     </div>
 </form>

您可以通过引用将您的post数据传递给这样的函数:

function checkFormValue(&$inputData) {  
    if (isset($inputData) && !empty($inputData)) {
        return $inputData;
    }
    
    return "";
}

$_POST数据上调用这个函数来验证它:

$catTitle = checkFormValue($_POST["cat_title"]);
var_dump($catTitle);

如果验证失败,则返回空字符串。使用此函数,您可以检查isset!empty的许多表单字段。

下面的代码会帮助你…

<?php
    function validate_post(){
        global $link;
        if (isset($_POST['submit'])) {
            $cat_err = "";
            if (!isset($_POST['cat_title']) || empty($_POST['cat_title']) || $_POST['cat_title']=="") {
                $cat_err = "field cannot be empty";
            } else {
                //check if a name only contains letters and whitespace
                if (!preg_match("/^[a-zA-Z]*$/", $_POST['cat_title'])) {
                    $cat_err = "Only letters and whitespace allowed";
                }
            }
            //if no errors found
            if ($cat_err=="") {
                $cat_title = htmlentities($_POST['cat_title']);
                  $sql = "INSERT INTO categories(cat_title)VALUES('$cat_title')";
                  $insert = mysqli_query($link, $sql);
                  confirm_query($insert);
                  if (mysqli_affected_rows($link) == 1) {
                      $cat_err = "Category has been added";
                      redirect("categories.php");
                  } else {
                      $cat_err = "Adding category failed";
                  }
            } else {
                $cat_err = "Field cannot be empty";
            }
            return $cat_err;
        }
    }
    ?>
    <?php $data=validate_post();echo $data;?><!-- call validate_post function-->
    <!-- ADD CATEGORY FORM -->
    <form action="" method="post">
        <div class="form-group">
            <label for="cat_tile">Categories</label>
            <input type="text" class="form-control" name="cat_title" id="cat_tile"/>
        </div>
        <div class="form-group">
            <input type="submit" class="btn btn-primary" value="+ Add Category" name="submit" >
        </div>
    </form>

你的函数没有返回任何信息。你需要告诉它返回错误,然后对它们做一些事情。您需要重新组织函数中消息的组织方式,但要点是:

return $error;添加到validate函数的末尾。

然后在页面正文中:

<?php $errors = validate_post(); ?><!-- call validate_post function-->
<!-- ADD CATEGORY FORM -->
<form action="" method="post">
   <?php  
   foreach($errors as $error)
   {
     echo $error;
   }
   ?>
    <div class="form-group">

因此,更改validate函数以将所有消息保存到单个数组中,返回该数组,然后处理这些项。

在函数内声明的变量只"存在"于该函数的作用域中。函数内的$post_info与函数外的$post_info没有关系

尝试传入$_POST数组:

if (isset($_POST['submit'])){
    validate_post($_POST)
}
function validate_post($post_array) {
  // your code here
}

Matt首先建议这样做,但是你可以这样做。

使用您的代码,这是您需要为该函数做的事情的概要。

<?php
function validate_post($link, $data=[]) {        
    $error = array();
    if (!isset($data['cat_title']) || empty($data['cat_title'])) {
        $error[] = "field cannot be empty";
    } else {
        //check if a name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z]*$/", $data['cat_title'])) {
            $cat_err = "Only letters and whitespace allowed";
        }
    }
    //if no errors found
    if (empty($error) && empty($cat_err)) {
        $cat_title = htmlentities($data['cat_title']);
        $sql = "INSERT INTO categories(cat_title)VALUES('$cat_title')";
        $insert = mysqli_query($link, $sql);
        confirm_query($insert); //This is another function you created???
        if (mysqli_affected_rows($link) == 1) {
            $post_info = "Category has been added";
            redirect("categories.php");
        } else {
            $post_info = "Adding category failed";
        }
    } else {
        $post_info = "Field cannot be empty";
    }   
}
if (isset($_POST['submit'])) {
    include 'dbfile.php'; // Containing your db link variable if that is how you've done it
    validate_post($link, $_POST); // Usually you need to pass your database link by reference also rather than by global.
}
?>
--html section--