Home >Backend Development >PHP Tutorial >Simply write a PHP verification class and teach you how to write a good PHP program (including multiple verification rules)_PHP Tutorial

Simply write a PHP verification class and teach you how to write a good PHP program (including multiple verification rules)_PHP Tutorial

WBOY
WBOYOriginal
2016-07-14 10:11:001137browse

Many people often only use simple js verification when developing websites. When you accidentally write an extra comma or period in js, ie6 will not recognize it and skip the verification directly. In fact, the safest way is to verify the data entered by the user on the server side. I wrote a simple PHP verification class, which contains a variety of verification rules for your reference. Original link


[php]
/**
* User input rule validation class
* author HaiNing Zhang
* date 2013-05-23
​*/
class Validate{
// Validation rules
Private $role_name = array(
// Verify whether it is empty <证>             'required',

// Matching the mailbox             'email',

// Matching ID card <配>              'idcode',

// matching numbers             'number',

// Matching http address
            'http',

// Match the QQ number <配>             'qq',

//Match Chinese postal code
             'postcode',

//Match ip address
            'ip',

//Match phone format
            'telephone',

// Matching the mobile phone format
            'mobile',

//Match 26 English letters
             'en_word',

// matching only Chinese
             'cn_word',

                              // Verify account (starting with a letter, consisting of alphanumeric and underscore, 4-20 bytes)
             'user_account',
);

/**
* [Verification function]
* @param [array] $data [Data to be verified by the user]
* @param [array] $validate_role [Validation rule]
* @param [array] $validate_err_msg [Error message]
* @return [bool] [Return true on success, error message on failure]
​​*/
Public function verify($data, $validate_role, $validate_err_msg=''){
If(empty($data)) return false;
If(empty($validate_role)) return false;
foreach ($data as $key => $value) {
              $key = strtolower($key);
foreach ($validate_role as $kk => $vv) {
                   $kk = strtolower($kk);
If($key == $kk){
                    foreach ($vv as $k => $v) { 
                        $k = strtolower($k); 
                        if( !in_array($k, $this->role_name)) return 'role name "'.$k.'" is not found!'; 
                        if($v == true){ 
                            if ( !$this->$k($value) ){ 
                                if (!isset($validate_err_msg[$kk][$k])) 
                                return 'var '.$key.' in '.$k.' of regular validation failure!'; 
                                return $validate_err_msg[$kk][$k]; 
                            } 
                        } 
                    } 
                } 
            } 
        } 
        return true; 
    } 
 
    // 获取规则数组  
    public function get_role_name(){ 
        return $this->role_name; 
    } 
 
    // 设置属性规则  
    public function set_role_name($arr){ 
        $this->role_name = array_merge($this->role_name, $arr); 
    } 
 
    // 验证是否为空  
    public function required($str){ 
        if(trim($str) != "") return true; 
        return false; 
    } 
 
    // 验证邮件格式  
    public function email($str){ 
        if(preg_match("/^([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+.[a-zA-Z]{2,3}$/", $str)) return true; 
        else return false; 
    } 
 
    // 验证身份证  
    public function idcode($str){ 
        if(preg_match("/^d{14}(d{1}|d{4}|(d{3}[xX]))$/", $str)) return true; 
        else return false; 
    } 
 
    // 验证http地址  
    public function http($str){ 
        if(preg_match("/[a-zA-Z]+://[^s]*/", $str)) return true; 
        else return false; 
    } 
 
    //匹配QQ号(QQ号从10000开始)  
    public function qq($str){ 
        if(preg_match("/^[1-9][0-9]{4,}$/", $str)) return true; 
        else return false; 
    } 
 
//Match Chinese postal code
Public function postcode($str){
If(preg_match("/^[1-9]d{5}$/", $str)) return true;
         else return false;
}  

//Match ip address
Public function ip($str){
If(preg_match("/^d{1,3}.d{1,3}.d{1,3}.d{1,3}$/", $str)) return true;
         else return false;
}  

// Match phone format
Public function telephone($str){
If(preg_match("/^d{3}-d{8}$|^d{4}-d{7}$/", $str)) return true;
         else return false;
}  

// Match mobile phone format
Public function mobile($str){
If(preg_match("/^(13[0-9]|15[0-9]|18[0-9])d{8}$/", $str)) return true;
         else return false;
}  

// Match 26 English letters
Public function en_word($str){
If(preg_match("/^[A-Za-z]+$/", $str)) return true;
         else return false;
}  

// Matches only Chinese
Public function cn_word($str){
If(preg_match("/^[x80-xff]+$/", $str)) return true;
         else return false;
}  

// Verify account (starting with a letter, consisting of alphanumeric and underscore, 4-20 bytes)
Public function user_account($str){
If(preg_match("/^[a-zA-Z][a-zA-Z0-9_]{3,19}$/", $str)) return true;
         else return false;
}  

// Verification number
Public function number($str){
If(preg_match("/^[0-9]+$/", $str)) return true;
         else return false;
}  
}

/**
* User input rule validation class
* author HaiNing Zhang
* date 2013-05-23
​*/
class Validate{
// Validation rules
private $role_name = array(
// Verify if it is empty
'required',

// Matching email address
'email',

// Match ID card
'idcode',

// Match numbers
'number',

// Match http address
'http',

// Match qq number
'qq',

//Match Chinese postal code
'postcode',

//Match ip address
'ip',

//Match phone format
'telephone',

// Match mobile phone format
'mobile',

//Match 26 English letters
'en_word',

// Matches only Chinese
'cn_word',

// Verify account (starting with a letter, consisting of alphanumeric and underscore, 4-20 bytes)
'user_account',
);

 /**
* [Verification function]
* @param [array] $data [Data that the user wants to verify]
* @param [array] $validate_role [Validation rule]
* @param [array] $validate_err_msg [Error message prompt]
* @return [bool] [Return true on success, error message on failure]
​*/
 public function verify($data, $validate_role, $validate_err_msg=''){
  if(empty($data)) return false;
  if(empty($validate_role)) return false;
  foreach ($data as $key => $value) {
   $key = strtolower($key);
   foreach ($validate_role as $kk => $vv) {
    $kk = strtolower($kk);
    if($key == $kk){
     foreach ($vv as $k => $v) {
      $k = strtolower($k);
      if( !in_array($k, $this->role_name)) return 'role name "'.$k.'" is not found!';
      if($v == true){
       if ( !$this->$k($value) ){
        if (!isset($validate_err_msg[$kk][$k]))
        return 'var '.$key.' in '.$k.' of regular validation failure!';
        return $validate_err_msg[$kk][$k];
       }
      }
     }
    }
   }
  }
  return true;
 }

 // 获取规则数组
 public function get_role_name(){
  return $this->role_name;
 }

 // 设置属性规则
 public function set_role_name($arr){
  $this->role_name = array_merge($this->role_name, $arr);
 }

 // 验证是否为空
 public function required($str){
  if(trim($str) != "") return true;
  return false;
 }

 // 验证邮件格式
 public function email($str){
  if(preg_match("/^([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+.[a-zA-Z]{2,3}$/", $str)) return true;
  else return false;
 }

 // 验证身份证
 public function idcode($str){
  if(preg_match("/^d{14}(d{1}|d{4}|(d{3}[xX]))$/", $str)) return true;
  else return false;
 }

 // 验证http地址
 public function http($str){
  if(preg_match("/[a-zA-Z]+://[^s]*/", $str)) return true;
  else return false;
 }

 //匹配QQ号(QQ号从10000开始)
 public function qq($str){
  if(preg_match("/^[1-9][0-9]{4,}$/", $str)) return true;
  else return false;
 }

 //匹配中国邮政编码
 public function postcode($str){
  if(preg_match("/^[1-9]d{5}$/", $str)) return true;
  else return false;
 }

 //匹配ip地址
 public function ip($str){
  if(preg_match("/^d{1,3}.d{1,3}.d{1,3}.d{1,3}$/", $str)) return true;
  else return false;
 }

 // 匹配电话格式
 public function telephone($str){
  if(preg_match("/^d{3}-d{8}$|^d{4}-d{7}$/", $str)) return true;
  else return false;
 }

 // 匹配手机格式
 public function mobile($str){
  if(preg_match("/^(13[0-9]|15[0-9]|18[0-9])d{8}$/", $str)) return true;
  else return false;
 }

 // 匹配26个英文字母
 public function en_word($str){
  if(preg_match("/^[A-Za-z]+$/", $str)) return true;
  else return false;
 }

 // 匹配只有中文
 public function cn_word($str){
  if(preg_match("/^[x80-xff]+$/", $str)) return true;
  else return false;
 }

// Verify account (starting with a letter, consisting of alphanumeric and underscore, 4-20 bytes)
public function user_account($str){
if(preg_match("/^[a-zA-Z][a-zA-Z0-9_]{3,19}$/", $str)) return true;
else return false;
}

// Verify number
public function number($str){
if(preg_match("/^[0-9]+$/", $str)) return true;
else return false;
}
}
Call method


[php]
require('model/Validate.php');
$data = array(
"username"=>'ningofaura@gmail.com',
"qq"=>'593084029',
"nickname"=>'Zhang Haining',
"id"=>'24',
);
$validate_role = array(
'username'=>array(
        'required'=>true,
        'email'=>true,
),
'qq'=>array(
        'required'=>true,
'qq'=>true,
),
'nickname'=>array(
        'required'=>true,
),
'id'=>array(
        'required'=>true,
         'number'=>true,
),
);

$validate_err_msg = array(
'username'=>array(
         'required'=>"Username cannot be empty",
        'email'=>"The email format is incorrect",
),
'qq'=>array(
        'required'=>"qq cannot be empty",
        'qq'=>"The qq format is incorrect",
),
'nickname'=>array(
'required'=>"Nickname cannot be empty",
),
'id'=>array(
        'required'=>"id cannot be empty",
        'number'=>"Not a number",
),
);
$Validate = new Validate();
$rt = $Validate->verify($data, $validate_role, $validate_err_msg);
if ($rt !== true){
echo $rt;
exit;
}

require('model/Validate.php');
$data = array(
    "username"=>'ningofaura@gmail.com',
    "qq"=>'593084029',
    "nickname"=>'张海宁',
    "id"=>'24',
    );
$validate_role = array(
    'username'=>array(
        'required'=>true,
        'email'=>true,
        ),
    'qq'=>array(
        'required'=>true,
        'qq'=>true,
        ),
    'nickname'=>array(
        'required'=>true,
        ),
    'id'=>array(
        'required'=>true,
        'number'=>true,
        ),
    );

$validate_err_msg = array(
    'username'=>array(
        'required'=>"用户名不能为空",
        'email'=>"邮箱格式不正确",
        ),
    'qq'=>array(
        'required'=>"qq不能为空",
        'qq'=>"qq格式不正确",
        ),
    'nickname'=>array(
        'required'=>"昵称不能为空",
        ),
    'id'=>array(
        'required'=>"id不能为空",
        'number'=>"不是数字",
        ),
    );
$Validate = new Validate();
$rt = $Validate->verify($data, $validate_role, $validate_err_msg);
if ($rt !== true){
    echo $rt;
    exit;
}

当然,如果你觉得验证无法满足你的需求,您还可以创建子类扩展您的方法


[php]
/**
* User database asynchronous verification
* author HaiNing Zhang
* date 2013-05-23
​*/
class AjaxValidate extends Validate{
Private $role_name = array(
                                                                                                                                                                                          // Verify whether the username exists
             'is_username',

                                                                 // Verify whether the nickname exists
            'is_nickname',
);

private $db;

Public function __construct(){
          $this->db = &load_system("Database");
             $this->set_role_name($this->role_name);
}  

// Determine whether the user name can be registered (to prevent duplicate user names)
Public function is_username($username){
           $_username = $this->db->filter('s', $username);
           $sql = "select id from user where username = ".$_username;
If($this->db->num_rows($sql)){
             return false;
         }else{
             return true;
         } 
}  

// Determine whether the nickname is available (to prevent duplicate nicknames)
Public function is_nickname($nickname){
$_nickname = $this->db->filter('s', $nickname);
          $sql = "select id from user where nickname =".$_nickname;
If($this->db->num_rows($sql)){
             return false;
         }else{
             return true;
         } 
}  
}

/**
* User database asynchronous verification
* author HaiNing Zhang
* date 2013-05-23
​*/
class AjaxValidate extends Validate{
private $role_name = array(
// Verify whether the username exists
'is_username',

// Verify whether the nickname exists
'is_nickname',
);

private $db;

public function __construct(){
$this->db = &load_system("Database");
$this->set_role_name($this->role_name);
}

// Determine whether the user name can be registered (to prevent duplicate user names)
public function is_username($username){
$_username = $this->db->filter('s', $username);
$sql = "select id from user where username=".$_username;
if($this->db->num_rows($sql)){
Return false;
}else{
Return true;
}
}

// Determine whether the nickname is available (to prevent duplicate nicknames)
public function is_nickname($nickname){
$_nickname = $this->db->filter('s', $nickname);
$sql = "select id from user where nickname=".$_nickname;
if($this->db->num_rows($sql)){
Return false;
}else{
Return true;
}
}
}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477434.htmlTechArticleMany people often just use simple js verification when developing websites. When you accidentally add too many errors in js If you write a comma or period, IE6 cannot recognize it and skip the verification directly. In fact, the safest...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn