/*** 身份证认证** @param $idcard* @return bool*/public function idcard_checksum18($idcard){$mainlandResult = false;$hongKongResult = false;$macaoResult = false;$taiwanResult = false;//大陆身份证判断if(strlen($idcard) ==18 ){$idcard_base=substr($idcard,0,17);if($this->idcard_verify_number($idcard_base)!=strtoupper(substr($idcard,17,1))){$mainlandResult = false;}else{$mainlandResult = true;}}//香港身份证$hongKongNumber = $idcard;if( strpos($hongKongNumber, "(") || strpos($hongKongNumber, ")") || strpos($hongKongNumber, "(") || strpos($hongKongNumber, ")") ){$hongKongNumber = str_replace('(', '', $hongKongNumber);$hongKongNumber = str_replace(')', '', $hongKongNumber);$hongKongNumber = str_replace('(', '', $hongKongNumber);$hongKongNumber = str_replace(')', '', $hongKongNumber);}if (preg_match("/^[a-zA-Z][0-9]{6}[0-9aA]$/", $hongKongNumber)) {$mul = 8;$sum = (ord(strtoupper($hongKongNumber))-64) * $mul;while($mul>1) {$sum += intval(substr($hongKongNumber, 8 - $mul, 1)) * $mul;$mul --;}$chksum = dechex(strval(11-($sum % 11)));//dec to hexif ($chksum == 'b') {$chksum = 0;}if($chksum == strtolower(substr($hongKongNumber, 7, 1))){$hongKongResult = true;}}//台湾身份证$taiwanId = $idcard;$d1 = substr($taiwanId,0,1);if( strlen($taiwanId) == 10 ) {if(stristr('ABCDEFGHJKLMNPQRSTUVXYWZIO',$d1) !== FALSE) {if( in_array(substr($taiwanId,1,1),[1,2])){if(is_numeric(substr($taiwanId,1,9))){$num = array ('A'=>'10','B'=>'11','C'=>'12','D'=>'13','E'=>'14','F'=>'15','G'=>'16','H'=>'17','J'=>'18','K'=>'19','L'=>'20','M'=>'21','N'=>'22', 'P'=>'23','Q'=>'24','R'=>'25','S'=>'26','T'=>'27','U'=>'28', 'V'=>'29','X'=>'30','Y'=>'31','W'=>'32','Z'=>'33','I'=>'34','O'=>'35',);$n1 = substr($num[$d1],0,1)+(substr($num[$d1],1,1)*9);unset($num,$d1);$n2=0;for($j=1;$j<9;$j++) {$d4=substr($taiwanId,$j,1);$n2=$n2+$d4*(9-$j);}$n3 = $n1+$n2+substr($taiwanId,9,1);if(($n3 % 10) == 0) {$taiwanResult = true;}}}}}//澳门身份证$macao = "/^[157][0-9]{6}\([0-9]\)$/";preg_match($macao,$idcard,$macaoMatch);if($macaoMatch){$macaoResult = true;}if($mainlandResult || $hongKongResult || $macaoResult || $taiwanResult ){return true;}return false;}// 计算身份证校验码,根据国家标准GB 11643-1999public function idcard_verify_number($idcard_base){if(strlen($idcard_base)!=17){return false;}//加权因子$factor=array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);//校验码对应值$verify_number_list=array('1','0','X','9','8','7','6','5','4','3','2');$checksum=0;for($i=0;$i<strlen($idcard_base);$i++){$checksum += substr($idcard_base,$i,1) * $factor[$i];}$mod=$checksum % 11;$verify_number=$verify_number_list[$mod];return $verify_number;}
如上图所示,idcard_checksum18($idcard) 方法适合大陆、香港、澳门、台湾四地身份证校验。