PHP 基本校驗

最壯程式設計師發表於2019-09-19

<?php

    class baseValidater

    {

          //最大引數個數

const MAX_ARGS=3;

public static function checkBool($var)

{

  return filter_var($var,FILTER_VALIDATE_BOOLEAN);

}

public static function checkInt($var)

{

  $args=func_get_args();

  if($var!=0) $var=ltrim($var,0);

  if(isset($args[1]))

  {

    if(isset($args[2]))

    {

      $options=array('options'=>array('min_range'=>$args[1],'max_range'=>$args[2]));

    }else{

      $options=array('options'=>array('min_range'=>$args[1]));

    }

    return filter_var($var,FILTER_VALIDATE_INT,$options);

  }else{

    return filter_var($var,FILTER_VALIDATE_INT);

  }

}

public static function checkNotInt($var)

{

  return !self::checkInt($var);

}

public static function checkFloat($var,$decimal=''){

  return filter_var($var,FILTER_VALIDATE_FLOAT,array('options'=>array('decimal'=>$decimal)));

}

public static function checkEmail($var)

{

  return filter_var($var,FILTER_VALIDATE_EMAIL);

}

public static function checkPhone($var)

{

  return (validater::checkTel($var) or validater::checkMobile($var));

}

public static function checkTel($var)

{

  //? 匹配0次或1次之前的原子 這個是配置是固定電話

  return preg_match("/^([0-9]{3,4}-?)?[0-9]{7,8}$/",$var)

}

public static function checkMobile($var)

{

  return preg_match("/^1[3-5,7,8]{1}[0-9]{9}$/",$var);

}

public static function checkURL($var)

{

  return filter_var($var,FILTER_VALIDATE_URL);

}

public static function checkDomain($var)

{

  return preg_match('/^([a-z0-9-]+.[a-z]{2,15})$/',$var);

}

public static function checkIP($var,$range='all')

{

  if($range=='all') return filter_var($var,FILTER_VALIDATE_IP);

   if($range=='public static')  return filter_var($var,FILTER_VALIDATE_IP,FILTER_FLAG_NO_PRIV_RANGE);

   if($range=='private')

  {

    if($var=='127.0.0.1' or filter_var($var,FILTER_VALIDATE_IP,FILTER_FLAG_NO_PRIV_RANG)==false) return true

    return false

  }

}

//身份證

public static function checkIdcard($idcard)

{

  if(strlen($idcard)!=18) return false;

  $idcard=strtoupper($idcard);

  $cityList=array(

      '11','12','13','14','15','21','22',

      '23','31','32','33','34','35','36',

      '37','41','42','43','44','45','46',

      '50','51','52','53','54','61','62',

      '63','64','65','71','81','82','91'

  );

  if(!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/')) return false;

  if(!in_array(substr($idcard,0,6),$cityList)) return false;

  $baseCode=substr($idcard,0,17);

  $verifyCode=substr($idcard,17,1);

  $interference=array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);

  $verifyConfig=array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');

  $total=0;

  for($i=0;$i<17;$i++) $total+=substr($baseCode,$i,1)*$interference[$i]';

  $mod=$total%11;

  return $verifyCode==$verifyConfig[$mod];

}

//substr(string,start,length)

public static function checkDate($date)

{

  if($date=='0000-00-00') return true;

  $stamp=strtotime($date);

  if(!is_numeric($stamp)) return false;

  return checkdate(date('m',$stamp),date('d',$stamp),date('Y',$stamp));

}

//檢查一些日期是否是有效的格利高裡日期:checkdate(月,日,年)

//date('m',時間戳)

public static function checkREG($var,$reg)

{

  return filter_var($var,FILTER_VALIDATE_REGEXP,array('options'=>array('regexp'=>$reg)));

}

//FILTER_VALIDATE_REGEXP 正規表示式

public static function checkLength($var,$max,$min=0)

{

  $length=function_exists('mb_strlen') ? mb_strlen($var,'utf-8'):strlen($var);

  return self::checkInt($length,$min,$max);

}

//注:strlen與mb_strlen是求字串長度的函式,在strlen計算時,對待一個UTF8的中文字元是3個長度,在mb_strlen計算時,選定內碼為UTF8,則會將一箇中文字元當作長度1來計算

public static function checkNotEmpty($var)

{

  return !empty($var);

}

//注:若變數不存在則返回 TRUE

// * 若變數存在且其值為""、0、"0"、NULL、、FALSE、 array()、$var; 以及沒有任何屬性的物件,則返回 TURE

// * 若變數存在且值不為""、0、"0"、NULL、、FALSE、 array()、$var; 以及沒有任何屬性的物件,則返回 FALSE

public static function checkEmpty($var)

{

  return empty($var);

}

public static function checkAccount($var)

{

  global $config;

  $accoutRule=empty($config->accountRule)?'|^[a-zA-Z0-9]{1}[a-zA-Z0-9.]{1,}[a-zA-Z0-9_]{1}$|' : $config->accountRule;

  return self::checkREG($var,$accountRule);

}

public static function checkCode($var)

{

  return self::checkREG($var,'|^[A-Za-z0-9]+$|');

}

public static function checkCaptcha($var)

{

  if(!isset($_SESSION['captcha'])) return false;

  return $var==$_SESSION['captcha'];

}

public static function checkEqual($var,$value)

{

  return $var==$value;

}

public static function checkNoEqual($var,$value)

{

  return $var!=$value;

}

public static function checkGT($var,$value)

{

  return $var>$value;

}

public static function checkLT($var,$value)

{

  return $var<$value;

}

public static function checkGE($var,$value)

{

  return $var>=$value;

}

public static function checkLE($var,$value)

{

  return $var<=$value;

}

public static funciton checkIn($var,$value)

{

  if(!is_array($value)) $value=explode(',',$value);

  return in_array($var,$value);

}

public static function checkFileName($var)

{

  return !preg_match('/>+|:+|<+/',$var);

}

//注:preg_match() 函式用於進行正規表示式匹配,成功返回 1 ,否則返回 0 。

public static function checkSensitive($vars,$dicts)

{

  foreach($vars as $var)

  {

    if(!$var) continue;

    foreach($dicts as $dict)

    {

      if(strpos($var,$dist)==false) continue;

      if(strpos($var,$dist)!==false) return false;

    }

  }

  return true;

}

//注:strpos() 函式查詢字串在另一字串中第一次出現的位置,返回字串在另一字串中第一次出現的位置,如果沒有找到字串則返回 FALSE。

public static function filterFiles()

{

  global $config;

  if(empty($_FILES)) return $_FILES;

  foreach($_FILES as $varName=$files)

  {

    if(is_array($files['name']))

    {

      foreach($files['name'] as $i=>$filename)

      {

        $extension=ltrim(strrchr($filename,'.'),'.');

        if(stripos(",{$config->file->dangers},",",{$extension},")!==false)

        {

          unset($_FILES);

          return array();

        }

      }

    }else{

      $extension=ltrim(strrchr($files['name'],'.'),'.');

      if(stripos(",{$config->file-dangers},",",{$extension},")!==false)

      {

        unset($_FILES);

        return array();

      }

    }

  }

  return $_FILES;

}

//注:strrchr搜尋某個字元在字串中的位置,並返回從該位置到字串結尾的所有字元

//strpos() 函式查詢字串在另一字串中第一次出現的位置(區分大小寫)

//stripos() - 查詢字串在另一字串中第一次出現的位置(不區分大小寫)

//strripos() - 查詢字串在另一字串中最後一次出現的位置(不區分大小寫)

//strrpos() - 查詢字串在另一字串中最後一次出現的位置(區分大小寫)

public static function filterSuper($super)

{

  if(!is_array($supper)) return $supper;

  $super=self::filterBadKeys($super);

  foreach($super as $key => $item)

  {

    if(is_array($item))

    {

      $item=self::filterBadKeys($item);

      foreach($item as $subkey=>$subItem)

      {

        if(is_array($subItem)) continue;

        $subItem=self::filterTrojan($subItem);

        $super[$key][$subkey]=self::filterXSS($subItem);

      }

    }else{

      $item=self::filterTrojan($item);

      $super[$key][$subkey]=self::filterXSS($item);

    }

  }

  return $super;

}

public static function filterBadKeys($var)

{

  global $config;

  if(empty( $config->framework->filterBadKeys)) return $var;

  foreach($var as $key=>$value) if(pregmatch('/[^a-zA-Z0-9.-]/',$key)) unset($var[$key]);

  return $var;

}

public static function filterXSS($var)

{

  global $config;

  if(empty($config->framework->filterXSS)) return $var;

  if(stripos($var,'<script')!==false)

  {

    $var =(string)$var;

        $evils = array('appendchild(', 'createElement(', 'xss.re', 'onfocus', 'onclick', 'innerHTML', 'replaceChild(', 'html(', 'append(', 'appendTo(', 'prepend(', 'prependTo(', 'after(', 'insertBefore', 'before(', 'replaceWith(');

        $replaces = array('a p p e n d c h i l d (', 'c r e a t e E l e m e n t (', 'x s s . r e', 'o n f o c u s', 'o n c l i c k', 'i n n e r H T M L', 'r e p l a c e C h i l d (', 'h t m l (', 'a p p e n d (', 'a p p e n d T o (', 'p r e p e n d (', 'p r e p e n d T o (', 'a f t e r (', 'i n s e r t B e f o r e(', 'b e f o r e (', 'r e p l a c e W i t h (');

        $var = str_ireplace($evils, $replaces, $var);

  }

  $var = preg_replace('/j\sa\sv\sa\ss\sc\sr\si\sp\st\s:/Ui', 'j a v a s c r i p t :', $var);

  return $var;

}

//注:str_ireplace(find,replace,string,count)

public static function filterParam($var,$type)

{

  global $config,$filter,$app;

  $moduleName=$app->getModuleName();

  $methodName=$app->getMethodName();

  $params=$app->getParams();

  if(type=='cookie')

  {

    $pagerCookie='pager'.ucfirst($moduleName).ucfirst($methodName);

    $filter->default->cookie[$pagerCookie]='int';

  }

  foreach($var as $key=>$value)

  {

    if($config->requestType=='GET' and $type=='get' and isset($params[$key])) continue;

    $rules='';

    if(isset($filter->{$moduleName}->{$methodName}->{$type}[$key]))

    {

      $rules=$filter->{$moduleName}->{$methodName}->{$type}[$key];

    }elseif(isset($filter->{$moduleName}->default->{$type}[$key]))

    {

      $rules=$filter->{$moduleName}->default->{$type}[$key];

    }else if(isset($filter->default->{$type}[$key]))

    {

      $rules=$filter->default->{$type}[$key];

    }

    if(!self::checkByRule($value,$rules)) unset($var[$key]);

  }

  return $var;

}

public static function checkByRule($var,$rule)

{

  if(empty($rule)) return false;

  list($operator,$param)=baseValidator::parseRuleString($rule);

  $checkMethod='check'.$operator;

  if(method_exists('baseValidater',$checkMethod))

  {

    if(empty($param) and self::$checkMethod($var)==false) return false;

    if(!empty($param) and self::$checkMethod($var,$param)===false) return false;

  }else if(functionexists('is'.$operator))

  {

    $checkFunction='is_'.$operator;

    if(!$checkFunction($var)) return false;

  }else{

    return false;

  }

  return true;

}

public static function parseRuleString($rule)

{

  global $filter;

  if(strpos($rule,'::')!==false) list($operator,$param)=explode('::',$rule);

  if(strpos($rule,'::')===false) list($operator,$param)=array($rule,'');

  if($operator=='reg' and isset($filter->rules->param)) $param=$filter->rules->$param;

  return array($operator,$param);

}

//注:list() 函式用於在一次操作中給一組變數賦值。 list(var1,var2...)

public static function call($var,$func)

{

  return filter_var($var,FILTER_CALLBACK,array('options'=>$func));

}

}

相關文章