以前我要验证身份证我们多半会使用正则判断用户输入是不是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)));
- }
-
-
-
- public static function to18Card($card) {
- $card = trim($card);
-
- if (strlen($card) == 18) {
- return $card;
- }
-
- if (strlen($card) != 15) {
- return false;
- }
-
-
- 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;
- }
-
-
- 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;
- }
- }
-
- ?>
|