php不用正则验证真假身份证
程序员文章站
2023-11-02 16:31:58
直接看代码吧,很简单的一个php类
复制代码 代码如下:
<?php
$idcard = new idcard();
var_dump($idcard::iscard($_get['card']));
/**
* 身份证处理类
*/
class idcard {
//检证身份证是否正确
public static function iscard($card) {
$card = self::to18card($card);
if (strlen($card) != 18) {
return false;
}
$cardbase = substr($card, 0, 17);
return (self::getverifynum($cardbase) == strtoupper(substr($card, 17, 1)));
}
//格式化15位身份证号码为18位
public static function to18card($card) {
$card = trim($card);
if (strlen($card) == 18) {
return $card;
}
if (strlen($card) != 15) {
return false;
}
// 如果身份证顺序码是996 997 998 999,这些是为百岁以上老人的特殊编码
if (array_search(substr($card, 12, 3), array('996', '997', '998', '999')) !== false) {
$card = substr($card, 0, 6) . '18' . substr($card, 6, 9);
} else {
$card = substr($card, 0, 6) . '19' . substr($card, 6, 9);
}
$card = $card . self::getverifynum($card);
return $card;
}
// 计算身份证校验码,根据国家标准gb 11643-1999
private static function getverifynum($cardbase) {
if (strlen($cardbase) != 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($cardbase); $i++) {
$checksum += substr($cardbase, $i, 1) * $factor[$i];
}
$mod = $checksum % 11;
$verify_number = $verify_number_list[$mod];
return $verify_number;
}
}
?>
直接看代码吧,很简单的一个php类
复制代码 代码如下:
<?php
$idcard = new idcard();
var_dump($idcard::iscard($_get['card']));
/**
* 身份证处理类
*/
class idcard {
//检证身份证是否正确
public static function iscard($card) {
$card = self::to18card($card);
if (strlen($card) != 18) {
return false;
}
$cardbase = substr($card, 0, 17);
return (self::getverifynum($cardbase) == strtoupper(substr($card, 17, 1)));
}
//格式化15位身份证号码为18位
public static function to18card($card) {
$card = trim($card);
if (strlen($card) == 18) {
return $card;
}
if (strlen($card) != 15) {
return false;
}
// 如果身份证顺序码是996 997 998 999,这些是为百岁以上老人的特殊编码
if (array_search(substr($card, 12, 3), array('996', '997', '998', '999')) !== false) {
$card = substr($card, 0, 6) . '18' . substr($card, 6, 9);
} else {
$card = substr($card, 0, 6) . '19' . substr($card, 6, 9);
}
$card = $card . self::getverifynum($card);
return $card;
}
// 计算身份证校验码,根据国家标准gb 11643-1999
private static function getverifynum($cardbase) {
if (strlen($cardbase) != 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($cardbase); $i++) {
$checksum += substr($cardbase, $i, 1) * $factor[$i];
}
$mod = $checksum % 11;
$verify_number = $verify_number_list[$mod];
return $verify_number;
}
}
?>
另外,关于身份证号验证本站还提供了身份证归属地查询工具如下: