写了一个身份证号验证类,php小白,写的不好,欢迎各位大神给我多提意见和建议 身份证号分为四部分,第一部分是前6位为地址码,7-14位是出生日期,15-17位是同一地方同一天出生的男孩为奇数,女孩是偶数,第18位是校验码,校验码的计算是前17位数字各自乘以各自对应位置上的加权因子值并求和,所求得的和跟11取余,根据余数再通过换算表得出第18位的校验码值。下面是具体的实现代码:

 <?php
header("Content-type: text/html; charset=utf-8");
date_default_timezone_set("PRC");
class Check{
//判断身份证长度
private function judgelen($idcard){
if(strlen($idcard)==15){
return true;
}else if(strlen($idcard)==18){
return true;
}else{
return false;
}
} //删除空格
function trimall($str)
{
$str_pre=array(" "," ","\t","\n","\r");
$str_later=array("","","","","");
return str_replace($str_pre,$str_later,$str);
} //校验地址码
private function checkAddr($idcard){ $addrcode="\"".substr($idcard,0,6)."\"";
$cmd="find /c ".$addrcode." ./cityId.txt";//该文件是全国各地对应的地址码
//echo `find /c "610404" ./cityId.txt`;
if($this->trimall(shell_exec(trim($cmd)))=="----------./CITYID.TXT:0"){
return false;
}else{
return true;
}
} //判断出生日期
private function checkBorn($idcard){
$borncode=substr($idcard,6,8);
if((strtotime($borncode)?0:-1)==-1)
return false;
else
return true;
} //判断校验码
private function checkCode($idcard){
$sum=0;
$check_array = array("0"=>1,"1"=>0,"2"=>'X',"3"=>9,"4"=>8,"5"=>7,"6"=>1,"7"=>5,"8"=>4,"9"=>3,"10"=>2,);//X对应的换算表
$ai_array = str_split($idcard,1);
$wi = array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);//各位置上对应的加权因子
for($i=0;$i<count($wi);$i++){
$sum+=$ai_array[$i]*$wi[$i];
}
$avg=$sum%11;
if($check_array[$avg]==array_pop($ai_array)){
return true;
}else{
return false;
}
} function checkid($idcard){
if($this->judgelen($idcard)){
if($this->checkAddr($idcard)){
if($this->checkBorn($idcard)){
if($this->checkCode($idcard)){
echo "验证成功";
}else{
echo "校验码验证失败";
}
}else{
echo "日期验证失败";
}
}else{
echo "地址码验证失败";
}
}else{
echo "长度验证失败";
} }
} $check = new check();
$check->checkid(身份证号);
?>
05-11 16:59