这篇文章给大家分享的是有关php中如何使用filter_var实现参数验证的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
先看看代码:
<?php
class 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";
}
?>
上面的代码,可直接运行。
使用方法:
建议把filter_param放到公共函数库中。
建议在每个model里都有个checkParam函数,专门配置验证规则。
感谢各位的阅读!关于“php中如何使用filter_var实现参数验证”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!