1. 程式人生 > 其它 >PHP-驗證身份證號碼

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;
}
如果您看了本篇部落格,覺得對您有所收穫,請點選右下角的[推薦]
如果您想轉載本部落格,請註明出處
如果您對本文有意見或者建議,歡迎留言
感謝您的閱讀