123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127 |
- <?php
- namespace liuniu;
- class IdentityCard
- {
-
- public static function isValid(string $num)
- {
-
- $length = strlen($num);
- if ($length == 15) {
-
- if (!is_numeric($num)) {
- return false;
- }
-
- $areaNum = substr($num, 0, 6);
-
- $dateNum = substr($num, 6, 6);
- } else if ($length == 18) {
-
- if (!preg_match('/^\d{17}[0-9xX]$/', $num)) {
- return false;
- }
-
- $areaNum = substr($num, 0, 6);
-
- $dateNum = substr($num, 6, 8);
- } else {
- return false;
- }
-
- if (!self::isAreaCodeValid($areaNum)) {
- return false;
- }
-
- if (!self::isDateValid($dateNum)) {
- return false;
- }
-
- if (!self::isVerifyCodeValid($num)) {
- return false;
- }
- return true;
- }
-
- private static function isAreaCodeValid(string $area) {
- $provinceCode = substr($area, 0, 2);
-
- if (11 <= $provinceCode && $provinceCode <= 65) {
- return true;
- } else {
- return false;
- }
- }
-
- private static function isDateValid(string $date) {
- if (strlen($date) == 6) {
- $date = '19'.$date;
- }
- $year = intval(substr($date, 0, 4));
- $month = intval(substr($date, 4, 2));
- $day = intval(substr($date, 6, 2));
-
- if (!checkdate($month, $day, $year)) {
- return false;
- }
-
- $currYear = date('Y');
- if ($year > $currYear) {
- return false;
- }
- return true;
- }
-
- private static function isVerifyCodeValid(string $num)
- {
- if (strlen($num) == 18) {
- $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($num{$i}) * $factor[$i];
- }
- $mod = $checkSum % 11;
- $token = $tokens[$mod];
- $lastChar = strtoupper($num{17});
- if ($lastChar != $token) {
- return false;
- }
- }
- return true;
- }
- }
|