doudi2833 2013-12-02 12:46
浏览 32
已采纳

php验证类未正确验证

am using a PHP validation class which i got from the internet, but am having some trouble,

am expecting to get this msg when nothing is entered to the form fields(fieldname is not set), but it display nothing if the type is string. and it display (fieldname is an invalid number) if the type is numeric

when somethind is entered and the type is string or type is numeric it prints (fieldname is too long) even if i didn't specify the min and max,

i also get this notice from my validation class

   Notice: Undefined index: min in C:\xampp\htdocs\RIS\class\validation.. 

Notice: Undefined index: min in C:\xampp\htdocs\RIS\class\validation

this is my **validation file**

    <?php

    class validation{

    /*
    * @errors array
    */
    public $errors = array();

    /*
    * @the validation rules array


     */
        private $validation_rules = array();

        /*
         * @the sanitized values array
         */
        public $sanitized = array();

        /*
         * @the source 
         */
        private $source = array();


        /**
         *
         * @t

he constructor, duh!
     *
     */
    public function __construct()
    {
    }

    /**
     *
     * @add the source
     *
     * @paccess public
     *
     * @param array $source
     *
     */
    public function addSource($source, $trim=false)
    {
        $this->source = $source;
    }


    /**
     *
     * @run the validation rules
     *
     * @access public
     *
     */
    public function run()
    {
        /*** set the vars ***/
        foreach( new ArrayIterator($this->validation_rules) as $var=>$opt)
        {
            if($opt['required'] == true)
            {
                $this->is_set($var);
            }

            /*** Trim whitespace from beginning and end of variable ***/
            if( array_key_exists('trim', $opt) && $opt['trim'] == true )
            {
                $this->source[$var] = trim( $this->source[$var] );
            }

            switch($opt['type'])
            {
                case 'email':
                    $this->validateEmail($var, $opt['required']);
                    if(!array_key_exists($var, $this->errors))
                    {
                        $this->sanitizeEmail($var);
                    }
                    break;

                case 'url':
                    $this->validateUrl($var);
                    if(!array_key_exists($var, $this->errors))
                    {
                        $this->sanitizeUrl($var);
                    }
                    break;

                case 'numeric':
                    $this->validateNumeric($var, $opt['min'], $opt['max'], $opt['required']);
                    if(!array_key_exists($var, $this->errors))
                    {
                        $this->sanitizeNumeric($var);
                    }
                    break;

                case 'string':
                    $this->validateString($var, $opt['min'], $opt['max'], $opt['required']);
                    if(!array_key_exists($var, $this->errors))
                    {
                        $this->sanitizeString($var);
                    }
                break;

                case 'float':
                    $this->validateFloat($var, $opt['required']);
                    if(!array_key_exists($var, $this->errors))
                    {
                        $this->sanitizeFloat($var);
                    }
                    break;

                case 'ipv4':
                    $this->validateIpv4($var, $opt['required']);
                    if(!array_key_exists($var, $this->errors))
                    {
                        $this->sanitizeIpv4($var);
                    }
                    break;

                case 'ipv6':
                    $this->validateIpv6($var, $opt['required']);
                    if(!array_key_exists($var, $this->errors))
                    {
                        $this->sanitizeIpv6($var);
                    }
                    break;

                case 'bool':
                    $this->validateBool($var, $opt['required']);
                    if(!array_key_exists($var, $this->errors))
                    {
                        $this->sanitized[$var] = (bool) $this->source[$var];
                    }
                    break;
            }
        }
    }


    /**
     *
     * @add a rule to the validation rules array
     *
     * @access public
     *
     * @param string $varname The variable name
     *
     * @param string $type The type of variable
     *
     * @param bool $required If the field is required
     *
     * @param int $min The minimum length or range
     *
     * @param int $max the maximum length or range
     *
     */
    public function addRule($varname, $type, $required=false, $min=0, $max=0, $trim=false)
    {
        $this->validation_rules[$varname] = array('type'=>$type, 'required'=>$required, 'min'=>$min, 'max'=>$max, 'trim'=>$trim);
        /*** allow chaining ***/
        return $this;
    }


    /**
     *
     * @add multiple rules to teh validation rules array
     *
     * @access public
     *
     * @param array $rules_array The array of rules to add
     *
     */
    public function AddRules(array $rules_array)
    {
        $this->validation_rules = array_merge($this->validation_rules, $rules_array);
    }

    /**
     *
     * @Check if POST variable is set
     *
     * @access private
     *
     * @param string $var The POST variable to check
     *
     */
    private function is_set($var)
    {
        if(!isset($this->source[$var]))
        {
            $this->errors[$var] = $var . ' is not set';
        }
    }



    /**
     *
     * @validate an ipv4 IP address
     *
     * @access private
     *
     * @param string $var The variable name
     *
     * @param bool $required
     *
     */
    private function validateIpv4($var, $required=false)
    {
        if($required==false && strlen($this->source[$var]) == 0)
        {
            return true;
        }
        if(filter_var($this->source[$var], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === FALSE)
        {
            $this->errors[$var] = $var . ' is not a valid IPv4';
        }
    }

    /**
     *
     * @validate an ipv6 IP address
     *
     * @access private
     *
     * @param string $var The variable name
     *
     * @param bool $required
     *
     */
    public function validateIpv6($var, $required=false)
    {
        if($required==false && strlen($this->source[$var]) == 0)
        {
            return true;
        }

        if(filter_var($this->source[$var], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === FALSE)
        {
            $this->errors[$var] = $var . ' is not a valid IPv6';
        }
    }

    /**
     *
     * @validate a floating point number
     *
     * @access private
     *
     * @param $var The variable name
     *
     * @param bool $required
     */
    private function validateFloat($var, $required=false)
    {
        if($required==false && strlen($this->source[$var]) == 0)
        {
            return true;
        }
        if(filter_var($this->source[$var], FILTER_VALIDATE_FLOAT) === false)
        {
            $this->errors[$var] = $var . ' is an invalid float';
        }
    }

    /**
     *
     * @validate a string
     *
     * @access private
     *
     * @param string $var The variable name
     *
     * @param int $min the minimum string length
     *
     * @param int $max The maximum string length
     *
     * @param bool $required
     *
     */
    private function validateString($var, $min=0, $max=0, $required=false)
    {
        if($required==false && strlen($this->source[$var]) == 0)
        {
            return true;
        }

        if(isset($this->source[$var]))
        {
            if(strlen($this->source[$var]) < $min)
            {
                $this->errors[$var] = $var . ' is too short';
            }
            elseif(strlen($this->source[$var]) > $max)
            {
                $this->errors[$var] = $var . ' is too long';
            }
            elseif(!is_string($this->source[$var]))
            {
                $this->errors[$var] = $var . ' is invalid';
            }
        }
    }

    /**
     *
     * @validate an number
     *
     * @access private
     *
     * @param string $var the variable name
     *
     * @param int $min The minimum number range
     *
     * @param int $max The maximum number range
     *
     * @param bool $required
     *
     */
    private function validateNumeric($var, $min=0, $max=0, $required=false)
    {
        if($required==false && strlen($this->source[$var]) == 0)
        {
            return true;
        }
        if(filter_var($this->source[$var], FILTER_VALIDATE_INT, array("options" => array("min_range"=>$min, "max_range"=>$max)))===FALSE)
        {
            $this->errors[$var] = $var . ' is an invalid number';
        }
    }

    /**
     *
     * @validate a url
     *
     * @access private
     *
      * @param string $var The variable name
     *
     * @param bool $required
     *
     */
    private function validateUrl($var, $required=false)
    {
        if($required==false && strlen($this->source[$var]) == 0)
        {
            return true;
        }
        if(filter_var($this->source[$var], FILTER_VALIDATE_URL) === FALSE)
        {
            $this->errors[$var] = $var . ' is not a valid URL';
        }
    }


    /**
     *
     * @validate an email address
     *
     * @access private
     *
     * @param string $var The variable name 
     *
     * @param bool $required
     *
     */
    private function validateEmail($var, $required=false)
    {
        if($required==false && strlen($this->source[$var]) == 0)
        {
            return true;
        }
        if(filter_var($this->source[$var], FILTER_VALIDATE_EMAIL) === FALSE)
        {
            $this->errors[$var] = $var . ' is not a valid email address';
        }
    }


    /**
     * @validate a boolean 
     *
     * @access private
     *
     * @param string $var the variable name
     *
     * @param bool $required
     *
     */
    private function validateBool($var, $required=false)
    {
        if($required==false && strlen($this->source[$var]) == 0)
        {
            return true;
        }
        filter_var($this->source[$var], FILTER_VALIDATE_BOOLEAN);
        {
            $this->errors[$var] = $var . ' is Invalid';
        }
    }

    ########## SANITIZING METHODS ############


    /**
     *
     * @santize and email
     *
     * @access private
     *
     * @param string $var The variable name
     *
     * @return string
     *
     */
    public function sanitizeEmail($var)
    {
        $email = preg_replace( '((?:
||\t|%0A|%0D|%08|%09)+)i' , '', $this->source[$var] );
        $this->sanitized[$var] = (string) filter_var($email, FILTER_SANITIZE_EMAIL);
    }


    /**
     *
     * @sanitize a url
     *
     * @access private
     *
     * @param string $var The variable name
     *
     */
    private function sanitizeUrl($var)
    {
        $this->sanitized[$var] = (string) filter_var($this->source[$var],  FILTER_SANITIZE_URL);
    }

    /**
     *
     * @sanitize a numeric value
     *
     * @access private
     *
     * @param string $var The variable name
     *
     */
    private function sanitizeNumeric($var)
    {
        $this->sanitized[$var] = (int) filter_var($this->source[$var], FILTER_SANITIZE_NUMBER_INT);
    }

    /**
     *
     * @sanitize a string
     *
     * @access private
     *
     * @param string $var The variable name
     *
     */
    private function sanitizeString($var)
    {
        $this->sanitized[$var] = (string) filter_var($this->source[$var], FILTER_SANITIZE_STRING);
    }

    } /*** end of class ***/

    ?>

my add_product.php file

    <?php 
    require_once'../core/config.php';
    require_once'../class/database.class.php';
    require_once'../class/validation.class.php';


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

    $name =$_POST['name'];
    $bprice =$_POST['bprice'];
    $sprice =$_POST['sprice'];
    $quantity =$_POST['quantity'];
    $exdate =$_POST['exdate'];
    $date_added =$_POST['date_added'];
    $type_id =$_POST['type_id'];


    $POST = array(
    'name' => $name,
    'bprice' => $bprice,
    'sprice' => $sprice,
    'quantity'=>$quantity,
    'exdate' => $exdate,
    'date_added' => $date_added,
    'type_id' => $type_id);


      /*** an array of rules ***/
       $rules_array = array(
        'name'=>array('type'=>'string',  'required'=>true,'trim'=>true),
        'bprice'=>array('type'=>'numeric', 'required'=>true,'trim'=>true),
        'sprice'=>array('type'=>'numeric', 'required'=>true, 'trim'=>true),
        'quantity'=>array('type'=>'numeric', 'required'=>true, 'trim'=>true),
        'exdate'=>array('type'=>'string', 'required'=>true,  'trim'=>true),
        'date_added'=>array('type'=>'string', 'required'=>true, 'trim'=>true),
        'type_id'=>array('type'=>'numeric', 'required'=>true, 'min'=>1,'trim'=>true)
        );

      /*** a new validation instance ***/
      $val = new validation;

      /*** use POST as the source ***/
      $val->addSource($POST);


      /*** add an array of rules ***/
     $val->addRules($rules_array);

    /*** run the validation rules ***/
    $val->run();

    /*** if there are errors show them ***/
    if(sizeof($val->errors) > 0)
    {
       foreach ($val->errors as $key => $value) {
          echo $value. ' '.'<br>';
       }
    }

    else{




    $database = new Database();

    $database->query("INSERT INTO  
            products(id,name,bprice,sprice,quantity,exdate,date_added,type_id)

         VALUES(:id,:name,:bprice,:sprice,:quantity,:exdate,:date_added,:type_id)");

    $database->bind('id','');
    $database->bind('name',$name);
    $database->bind('bprice',$bprice);
    $database->bind('sprice',$sprice);
    $database->bind('quantity',$quantity);
    $database->bind('exdate',$exdate);
    $database->bind('date_added',$date_added);
    $database->bind('type_id',$type_id);

    $database->execute();

    /*** show the array of validated and sanitized variables ***/
     print_r($val->sanitized);



          }

      }


    ?>

    <div id="contacts">
    <div class="row"><!-- Alignment -->
    <div class="col-sm-offset-3 col-sm-6">
      <!-- Form itself -->
    <form class="well"  method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>">

      <div class="controls">&nbsp;</div>
       <!-- Full Name -->
     <label class="control-label">Name</label>

       <div class="control-group">
    <div class="controls">
        <input class="form-control" id="name" type="text"
       placeholder="Name of product"    name="name" />

    </div>
    </div>

    <div class="controls">&nbsp;</div>


    <label class="control-label">Buying Price</label>

    <div class="control-group">
    <div class="controls">
        <input class="form-control" id="bprice" type="text"  
       placeholder="Enter Buying   Price" name="bprice" /></div>
    </div>

    <div class="controls">&nbsp;</div>

    <label class="control-label">Seling Price</label>

    <div class="control-group">
    <div class="controls">
        <input class="form-control" id="sprice" type="text"
     placeholder="Enter Selling Price" name="sprice" /></div>
    </div>

    <div class="controls">&nbsp;</div>

    <label class="control-label">Quantity</label>

   <div class="control-group">
    <div class="controls">
        <input class="form-control" id="quantity" type="text"
     placeholder="Enter Quantity" name="quantity" /></div>
    </div>


    <div class="controls">&nbsp;</div>

    <label class="control-label">Expire Date</label>

    <div class="control-group">
    <div class="controls">
        <input class="form-control" id="exdate" type="text"
     placeholder="Enter Expire Date" name="exdate" /></div>
    </div>

    <div class="controls">&nbsp;</div>

    <label class="control-label">Date Added</label>

    <div class="control-group">
    <div class="controls">
        <input class="form-control" id="date_added" type="text"
     placeholder="Enter Date added" name="date_added" /></div>
    </div>

    <div class="controls">&nbsp;</div>

    <label class="control-label">Type ID</label>

    <div class="control-group">
    <div class="controls">
        <input class="form-control" id="type_id" type="text" 
    placeholder="Enter Type ID" name="type_id" /></div>
    </div>


    <div class="controls">&nbsp;</div>

     <button class="btn btn-primary pull-left" type="submit" name="submit">Send</button>
    <div class="controls">&nbsp;</div>
    <div class="controls">&nbsp;</div>
    </form></div>
    </div>
   </div>

any help plz?

  • 写回答

2条回答 默认 最新

  • duan19913 2013-12-02 13:01
    关注

    It's perfectly simple. Whilst you're checking for some keys (array_key_exists('trim', $opt)) in the $opt array, you're just assuming the keys min and max to be set, always.
    For example here:

         case 'numeric':
                    $this->validateNumeric($var, $opt['min'], $opt['max'], $opt['required']);
    

    Yet you're passing the opt array without these both keys, save for 1 exception, where you specify a min value, but still no max.

    array(
        'name'=>array('type'=>'string',  'required'=>true,'trim'=>true),
        'bprice'=>array('type'=>'numeric', 'required'=>true,'trim'=>true),
        'sprice'=>array('type'=>'numeric', 'required'=>true, 'trim'=>true),
        'quantity'=>array('type'=>'numeric', 'required'=>true, 'trim'=>true),
        'exdate'=>array('type'=>'string', 'required'=>true,  'trim'=>true),
        'date_added'=>array('type'=>'string', 'required'=>true, 'trim'=>true),
        'type_id'=>array('type'=>'numeric', 'required'=>true, 'min'=>1,'trim'=>true)
        );
    

    You're not getting a fatal error, because PHP defaults the value of undefined indexes to null, but it will produce a notice, as you've noticed.
    The answer is to either introduce a check in your method:

    $opt['min'] = isset($opt['min']) ? $opt['min'] : 0;//default to 0
    $opt['max'] = isset($opt['max']) ? $opt['max'] : 0;//some def value
    

    or to pass the keys, always.
    Another way to deal with this would be to check if these values are set, and if not, not to perform min-max validation.

    Lastly, some might suggest suppressing the notice, or lowering the error reporting level. While debugging code, I just want to say, this is a terrible idea. Notices are tools to help you improve on your code. It means there's something wrong.
    If there's something not quite right, fix it, don't ignore it

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划