PHP表单数据验证

背景

  在上次项目的时候,一直不明白为什么要对数据验证,我能保证我每次请求的数据都是合法的,但是在后面的时候,原来“用户”并不是那样听话,他总是要给我们找麻烦,然后可能让我们的服务器崩掉。但是只对单个请求做数据验证,不能很好的统一管理,所有就想到了将验证信息提出来。以后每次直接调用就好。

验证类 Validator.class.php

该验证类中加入了XSS过滤,可以对参数进行过滤后验证,实现数据合理化 也可以调用setXss(false)关闭XSS过滤

 <?php

 /*************************************************
Validator for PHP 服务器端 【验证数据】
code by HoldKing
date:2016-06-01
*************************************************/ class Validator{ private static $_instance; //保存类实例的静态成员变量
private $error_msg = []; // 错误提示信息
private $xss = true; // 是否进行XSS的过滤 //private标记的构造方法
private function __construct(){
// echo 'This is a Constructed method. ';
} //创建__clone方法防止对象被复制克隆
public function __clone(){
die('Validator Clone is not allow!');
} //单例方法,用于访问实例的公共的静态方法
public static function getInstance(){
if(!(self::$_instance instanceof self)){
self::$_instance = new self;
}
return self::$_instance;
} //是否进行XSS的过滤
public function setXss($xss){
$this->xss = $xss;
} private function remove_xss($string) {
if( empty($string) ) return $string;
if( !$this->valiUrl($string) ) return $string; if( strstr($string, '%25') ){ $string = urldecode($string); }
$string = urldecode($string); $string = preg_replace('/<script[\w\W]+?<\/script>/si', '', $string);
$string = preg_replace("/'.*?'/si", '', preg_replace('/".*?"/si', '', $string) ); $string = strip_tags ( trim($string) );
$string = str_replace ( array ('"', "'", "\\", "..", "../", "./", "//", '/', '>'), '', $string ); $string = preg_replace ( '/%0[0-8bcef]/', '', $string );
$string = preg_replace ( '/%1[0-9a-f]/' , '', $string );
$string = preg_replace ( '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S', '', $string ); return $string;
} /*
* 添加数据与验证规则
* @param array $data 验证数据源 [&引用传递]
* @param array $gule 验证数据规则
*/
public function make(array &$data, array $gules){ if( !is_array($data) ){
$this->error_msg['datas'] = 'The datas is not array.';
return false;
} if( !is_array($gules) ){
$this->error_msg['gules'] = 'The gules is not array.';
return false;
} foreach($gules as $name => $gule){
if( !isset($data[$name]) ){
$this->error_msg[$name] = "We need to $name field in the datas";
continue ;
} if($this->xss){ // xss 过滤
$data[$name] = $this->remove_xss($data[$name]);
} $this->valiRun($gule, $data[$name], $name);
} } /*
* 查看是否有验证错误
* return bool
*/
public function fails(){
return count($this->error_msg);
} /*
* 查看是否有验证错误
* return array
*/
public function error(){
return $this->error_msg;
} /*
* 对数据进行验证规则验证
* @param int|string|... $data 验证数据
* @param string $gule 验证规则字符串
* @param string $name 验证数据键名
* return bool
*/
private function valiRun($gule, $data, $name){
// 拆分多个验证规则
$gule = explode('|', $gule);
foreach($gule as $method){ @list($method, $param) = explode(':', $method);
$valiMethod = 'vali' . ucwords($method) ;
if( method_exists($this, $valiMethod) ){
if( $this->$valiMethod($data, $param) ){
$this->doMessage($name, $method, $param);
break ;
}
continue ;
} $this->error_msg[$name] = "Method [$method] does not exist.";
}
} private function doMessage($attribute, $method, $param = ''){
if( $param == '' ){
$this->error_msg[$attribute] = "The $attribute field must be $method.";
}else{
$param = str_replace(':attribute', $attribute, $param);
$this->error_msg[$attribute] = $param;
}
} /********** 规则验证 直接验证 *************/
private function valiRequired($str, $param=null){
return empty($str);
}
private function valiString($str, $param=null){
return !is_string($str);
}
private function valiInt($str, $param=null){
return $str != (int)$str;
}
private function valiNumeric($str, $param=null){
return !is_numeric($str);
}
private function valiArray($str, $param=null){
return !is_array($str);
}
private function valiEmail($str, $param=null){
return !preg_match("/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/", $str);
}
private function valiUrl($str, $param=null){
return !preg_match("/^https?:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"])*$/", $str);
}
private function valiQq($str, $param=null){
return !preg_match("/^[1-9]\d{4,8}$/", $str);
}
private function valiZip($str, $param=null){
return !preg_match("/^[1-9]\d{5}$/", $str);
}
private function valiIdcard($str, $param=null){
return !preg_match("/^\d{17}[X0-9]$/", $str);
}
private function valiChinese($str, $param=null){
return !ereg("^[".chr(0xa1)."-".chr(0xff)."]+$", $str);
}
private function valiMobile($str, $param=null){
return !preg_match("/^((\(\d{3}\))|(\d{3}\-))?13\d{9}$/", $str);
}
private function valiPhone($str, $param=null){
return !preg_match("/^((\(\d{3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}$/", $str);
}
private function valiDate($str, $param=null){
return !preg_match("/^\d{2}(\d{2})?-\d{1,2}-\d{1,2}(\s\d{1,2}:\d{1,2}(:\d{1,2})?)?$/", $str);
} /********** 规则验证 组合验证 *************/
private function valiMin($value, &$param ){
if( !is_numeric($param) ){
$param = "The :attribute need to number"; return true;
}
if($value < $param){
$param = "The :attribute[$value] must be more than $param"; return true;
}
}
private function valiMax($value, &$param){
if( !is_numeric($param) ){
$param = "The :attribute need to number"; return true;
}
if($value > $param){
$param = "The :attribute[$value] must be less than $param"; return true;
}
}
private function valiSize($value, &$param){
if( !is_numeric($param) ){
$param = "The :attribute need to number"; return true;
}
if( strlen($value) != $param ){
$param = "The :attribute[$value] length must be $param"; return true;
}
}
private function valiIn($value, &$param){
$params = explode(',', $param);
if( !is_array($params) || empty($param) || count($params) < 1 ){
$param = "Validation rule in requires at least 1 parameters."; return true;
}
if( !in_array($value, $params) ){
$param = "The :attribute[$value] must be one of the following: $param"; return true;
}
} private function valiBetween($value, &$param){
@list($min, $max) = explode(',', $param);
if( empty($min) || empty($max) ){
$param = "Validation rule between requires at least 2 parameters."; return true;
}
if( $value < $min || $value > $max ){
$param = "The :attribute[$value] must be between $min - $max."; return true;
}
}
private function valiAfter($value, &$param){
if( !$param || !preg_match("/^[\d-]{10}(\s[\d:]{8})?$/", $param) ){
$param = "Validation rule after requires date string."; return true;
}
if( strtotime($value) <= strtotime($param) ){
$param = "The :attribute[$value] must be after $param"; return true;
}
}
private function valiBefore($value, &$param){
if( !$param || !preg_match("/^[\d-]{10}(\s[\d:]{8})?$/", $param) ){
$param = "Validation rule after requires date string."; return true;
}
if( strtotime($value) >= strtotime($param) ){
$param = "The :attribute[$value] must be before $param"; return true;
}
} /******************* 规则验证 end ******************************************/ } ?>

使用示例

// 单例模式 获得单例实例
$Validator = Validator::getInstance(); // 验证数据源
$input['name'] = 'kingsoft<meta http-equiv="refresh" content="5;">';
$input['age'] = 10;
$input['type'] = "1'%22+onmouseover=alert()+d='%22";
$input['date'] = '2016-05-31 12:26:12"><script>alert(document.cookie)</script><!-';
$input['email'] = 'peng*@163.com';
print_r($input); // 开始验证
$Validator->make($input, array(
'name' => 'required|string|size:4',
'age' => 'min:5|max:99',
'email' => 'email',
'type' => 'in:0,1',
'date' => 'date'
)); // 判断是否验证通过
if( $Validator->fails() ){
print_r( $Validator->error() );
} // XSS标记被过滤后数据
print_r($input);

运行结果

 Array
(
[name] => kingsoft<meta http-equiv="refresh" content="5;">
[age] => 10
[type] => 1'%22+onmouseover=alert()+d='%22
[date] => 2016-05-31 12:26:12"><script>alert(document.cookie)</script><!-
[email] => peng*@163.com
) Array
(
[name] => The name[kingsoft] length must be 4
) Array
(
[name] => kingsoft
[age] => 10
[type] => 1
[date] => 2016-05-31 12:26:12
[email] => peng*@163.com
)

我们可以看出:

1. name字段没有验证通过,是因为他的长度为8并不是4, 而且支持多种规则验证【组合验证】,这样我们就不用针对不同的情况使用if...else 来判断验证了。

2. 验证结束后的数据与源数据存在差异,我们分析出,这些差异在表单中是不能出现的非法【Xss】攻击数据,所以进行XSS攻击过滤。如果非要使用这些数据内容验证,可以关闭xss过滤,使用原样数据验证。

3. 不支持单个字段关闭xss过滤; 不支持数组字段过滤。

上一篇:opencv-python教程学习系列10-颜色空间转换


下一篇:Rop 文件上传解决思路