php 验证二代身份证号

180it 2020-10-01 PM 1649℃ 0条
/**
 * 验证身份证号
 * https://gist.github.com/lmh3/331d225f4f63eed7e6152a35ab625906
 *
 * @param string|int  $code  身份证号码
 * @return bool
 */
function validator_idcard($code) : bool {
    $code = strval($code);

    if(strlen($code) !== 18 || !preg_match('/^\d+$/i', substr($code, 0, -1))) {
        return false;
    }

    $year = intval(substr($code, 6, 4));
    $month = intval(substr($code, 10, 2));
    $day = intval(substr($code, 12, 2));

    if(!checkdate($month, $day, $year)) {
        return false;
    }

    $weight = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];

    $sum = 0;

    for($i = 0; $i < 17; $i++) {
        $sum += $code[$i] * $weight[$i];
    }

    $checkBits = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];

    if ($checkBits[$sum % 11] !== $code[17]) {
        return false;
    }

    return true;
}
支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

php 验证二代身份证号