php verify ID card function

高洛峰
Release: 2023-03-05 15:30:01
Original
2658 people have browsed it

Share an identity number verification function:

function validateIdCard($value)
{
    if (!preg_match('/^\d{17}[0-9xX]$/', $value)) { //基本格式校验
        return false;
    }

    $parsed = date_parse(substr($value, 6, 8));
    if (!(isset($parsed['warning_count']) 
        && $parsed['warning_count'] == 0)) { //年月日位校验
        return false;
    }

    $base = substr($value, 0, 17);

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

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

    $checkSum = 0;
    for ($i=0; $i<17; $i++) {
        $checkSum += intval(substr($base, $i, 1)) * $factor[$i];
    }

    $mod = $checkSum % 11;
    $token = $tokens[$mod];

    $lastChar = strtoupper(substr($value, 17, 1));

    return ($lastChar === $token); //最后一位校验位校验
}
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!