function
IdCodeValid(
$code
){
// var_dump((int)substr($code,10,2));die;
//
身份证号合法性验证
//
支持
15
位和
18
位身份证号
//
支持地址编码、出生日期、校验位验证
$city=
[
11
=>
"
北京
"
,
12
=>
"
天津
"
,
13
=>
"
河北
"
,
14
=>
"
山西
"
,
15
=>
"
内蒙古
"
,
21
=>
"
辽宁
"
,
22
=>
"
吉林
"
,
23
=>
"
黑龙江
"
,
31
=>
"
上海
"
,
32
=>
"
江苏
"
,
33
=>
"
浙江
"
,
34
=>
"
安徽
"
,
35
=>
"
福建
"
,
36
=>
"
江西
"
,
37
=>
"
山东
"
,
41
=>
"
河南
"
,
42
=>
"
湖北
"
,
43
=>
"
湖南
"
,
44
=>
"
广东
"
,
45
=>
"
广西
"
,
46
=>
"
海南
"
,
50
=>
"
重庆
"
,
51
=>
"
四川
"
,
52
=>
"
贵州
"
,
53
=>
"
云南
"
,
54
=>
"
西藏
"
,
61
=>
"
陕西
"
,
62
=>
"
甘肃
"
,
63
=>
"
青海
"
,
64
=>
"
宁夏
"
,
65
=>
"
新疆
"
,
71
=>
"
台湾
"
,
81
=>
"
香港
"
,
82
=>
"
澳门
"
,
91
=>
"
国外
"
];
$row=
[
'pass'
=>true
,
'msg'
=>
'
验证成功
'
];
if
(
!$code || !
preg_match(
'/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/'
,
$code
)){
$row=
[
'pass'
=>false
,
'msg'
=>
'
身份证号格式错误
'
];
}
elseif
(
!$city
[substr(
$code
,
0
,
2
)]
|| (int)
substr(
$code
,
10
,
12
)
>
12
){
$row=
[
'pass'
=>false
,
'msg'
=>
'
身份证号地址编码错误
'
];
}
return $row
;
}
方法二
//
验证身份证是否有效
function
validateIDCard(
$IDCard
) {
if
(strlen(
$IDCard
)
==
18
) {
return
check18IDCard(
$IDCard
);
}
elseif
((strlen(
$IDCard
)
==
15
)) {
$IDCard =
convertIDCard15to18(
$IDCard
);
return
check18IDCard(
$IDCard
);
}
else
{
return false
;
}
}
//
计算身份证的最后一位验证码
,
根据国家标准
GB 11643-1999
function
calcIDCardCode(
$IDCardBody
) {
if
(strlen(
$IDCardBody
)
!=
17
) {
return false
;
}
//
加权因子
$factor = array
(
7
,
9
,
10
,
5
,
8
,
4
,
2
,
1
,
6
,
3
,
7
,
9
,
10
,
5
,
8
,
4
,
2
);
//
校验码对应值
$code = array
(
'1'
,
'0'
,
'X'
,
'9'
,
'8'
,
'7'
,
'6'
,
'5'
,
'4'
,
'3'
,
'2'
);
$checksum =
0
;
for
(
$i =
0
;
$i <
strlen(
$IDCardBody
);
$i++
) {
$checksum +=
substr(
$IDCardBody
,
$i
,
1
)
* $factor
[
$i
];
}
return $code
[
$checksum %
11
];
}
//
将
15
位身份证升级到
18
位
function
convertIDCard15to18(
$IDCard
) {
if
(strlen(
$IDCard
)
!=
15
) {
return false
;
}
else
{
//
如果身份证顺序码是
996 997 998 999
,这些是为百岁以上老人的特殊编码
if
(array_search(substr(
$IDCard
,
12
,
3
),
array
(
'996'
,
'997'
,
'998'
,
'999'
))
!== false
) {
$IDCard =
substr(
$IDCard
,
0
,
6
)
.
'18'
.
substr(
$IDCard
,
6
,
9
);
}
else
{
$IDCard =
substr(
$IDCard
,
0
,
6
)
.
'19'
.
substr(
$IDCard
,
6
,
9
);
}
}
$IDCard = $IDCard .
calcIDCardCode(
$IDCard
);
return $IDCard
;
}
// 18
位身份证校验码有效性检查
function
check18IDCard(
$IDCard
) {
if
(strlen(
$IDCard
)
!=
18
) {
return false
;
}
$IDCardBody =
substr(
$IDCard
,
0
,
17
);
//
身份证主体
$IDCardCode =
strtoupper(substr(
$IDCard
,
17
,
1
));
//
身份证最后一位的验证码
if
(calcIDCardCode(
$IDCardBody
)
!= $IDCardCode
) {
return false
;
}
else
{
return true
;
}
}
var_dump(validateIDCard(
'123456789987654321'
));
die
;