【php】用filter_var實現的簡單參數驗證

來源:互聯網
上載者:User

標籤:blog   http   io   使用   ar   for   sp   div   c   

filter_var是在php5.2.0中開始提供的。詳細說明見:

http://www.php.net/manual/zh/book.filter.php

先看看代碼:

 

<?phpclass Utils {    /**     * 主要是調用filter_var_array驗證,再擴充一個required欄位來表示必填項。     * http://www.php.net/manual/zh/book.filter.php     * 注意: (可以不傳,但不能傳錯)     *  1.先驗證格式,有失敗的拋異常。     *  2.未傳的參數,有default的(不管是否required=1),則設定為default值。     * 樣本:     *      $filterArr = array(     *          "pn" =>array(     *              "required"  => 1,     *              "filter"    => FILTER_VALIDATE_INT,     *              "options"   => array(     *                  "default"   =>1,     *                  "min_range" =>1,     *              )     *          )     *      )     */public static function filter_param($paramArr, $filterArr){        $res = filter_var_array($paramArr, $filterArr);     //參數不合法-flase, 沒傳參數-null        foreach($res as $key=>$val){            //如果有驗證失敗的,拋出異常。            if(false === $val){                throw new Exception( "Utils::filter_param: failed, key=$key ");            }            //再判斷未傳的參數。            if( is_null($val)){                //1.如果是必填項                if($filterArr[$key][‘required‘] ){                    if(isset($filterArr[$key][‘options‘][‘default‘])){                        //1.1如果有default值,則設定為default值。                        $res[$key] = $filterArr[$key][‘options‘][‘default‘];                    }else{                        //1.2如果沒有default值,拋出異常。                        throw new Exception( "Utils::filter_param: Do not have required param, key=$key" );                    }                }else{                    //$res[$key]=‘‘;      //這裡是預設把null值改為空白值。是否有必要?                }            }        }        return $res;}};            //每個model裡,都寫個checkParam函數,用來配置驗證的規則。    function checkParam($arrInput){        //1.先檢查catId        $filter = array(                //數字類型的,必填。只允許 0-1。            "catId" => array(                "required"=>1,                "filter"=>FILTER_VALIDATE_INT,                "options"=>array(                    "min_range" =>0,                    "max_range" =>1,                )            ),                //字串類型的,必填。長度大於1。            "title" => array(                "required"=>1,                "filter"=>FILTER_VALIDATE_REGEXP,                "options"=>array(                    "regexp" =>"/^.+/",                )            ),                //字串類型的,非必填。但要是填了的話,則格式必須為email。            "email" => array(                "filter"=>FILTER_VALIDATE_EMAIL,            ),        );        $_res = Utils::filter_param($arrInput, $filter) ;    }             //比如這個是輸入的參數。可以試著修改這裡看看效果。    $arrInput=array(        ‘catId‘=>1,        ‘title‘=>‘xx‘,        ‘email‘=>‘xxxxxx.com‘,    );    try{        $res=checkParam($arrInput);        echo "驗證通過,繼續其它代碼...\n";    }catch(Exception $e){        echo ‘Caught exception: ‘,  $e->getMessage(), "\n";    }?>

  

上面的代碼,可直接運行。

使用方法:

  1. 建議把filter_param放到公用函數庫中。
  2. 建議在每個model裡都有個checkParam函數,專門配置驗證規則。

【php】用filter_var實現的簡單參數驗證

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.