以前我要驗證身份證我們多半會使用正則判斷用戶輸入是不是15位或18位的全數字,然後來判斷身份證是否合法了,這種方法只是最基礎的,下面提供的這個身份證驗證,可以識別真假身份證哦。
代碼如下
復制代碼
<?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;
}
}
?>