PHP-验证身份证号码

身份证号码格式校验用的是mod11-2算法

<?php
/**
 * 校验身份证号码格式是否正确
 * @param string $idcard
 * @return bool
 */
function checkIdcard($idcard)
{
    $idcard = strtoupper($idcard);
    if (!preg_match('#^d{17}(d|X)$#', $idcard)) {
        return false;
    }
    // 判断出生年月日的合法性(解决号码为666666666666666666也能通过校验的问题)
    $birth = substr($idcard, 6, 8);
    if ($birth < "19000101" || $birth > date("Ymd")) {
        return false;
    }
    $year = substr($birth, 0, 4);
    $month = substr($birth, 4, 2);
    $day = substr($birth, 6, 2);
    if (!checkdate($month, $day, $year)) {
        return false;
    }
    // 校验身份证格式(mod11-2)
    $check_sum = 0;
    for ($i = 0; $i < 17; $i++) {
        // $factor = (1 << (17 - $i)) % 11;
        $check_sum += $idcard[$i] * ((1 << (17 - $i)) % 11);
    }
    $check_code = (12 - $check_sum % 11) % 11;
    $check_code = $check_code == 10 ? 'X' : strval($check_code);
    if ($check_code !== substr($idcard, -1)) {
        return false;
    }
    return true;
}
如果您看了本篇博客,觉得对您有所收获,请点击右下角的[推荐]
如果您想转载本博客,请注明出处
如果您对本文有意见或者建议,欢迎留言
感谢您的阅读
原文地址:https://www.cnblogs.com/RainCry/p/15429433.html