份證號驗證(兼容15,18位) ,注冊驗證的時候可以用上。
01
//比較菜鳥 第一次分享代碼
02
//身份證號驗證
03
protected
function
checkIdCard(){
04
if
(
empty
(
$_POST
[
'idcard'
])){
05
return
false;
06
}
07
$idcard
=
$_POST
[
'idcard'
];
08
$City
=
array
(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=>
"國外"
);
09
$iSum
= 0;
10
$idCardLength
=
strlen
(
$idcard
);
11
//長度驗證
12
if
(!preg_match(
'/^\d{17}(\d|x)$/i'
,
$idcard
)
and
!preg_match(
'/^\d{15}$/i'
,
$idcard
))
13
{
14
return
false;
15
}
16
//地區驗證
17
if
(!
array_key_exists
(
intval
(
substr
(
$idcard
,0,2)),
$City
))
18
{
19
return
false;
20
}
21
// 15位身份證驗證生日,轉換為18位
22
if
(
$idCardLength
== 15)
23
{
24
$sBirthday
=
'19'
.
substr
(
$idcard
,6,2).
'-'
.
substr
(
$idcard
,8,2).
'-'
.
substr
(
$idcard
,10,2);
25
$d
=
new
DateTime(
$sBirthday
);
26
$dd
=
$d
->format(
'Y-m-d'
);
27
if
(
$sBirthday
!=
$dd
)
28
{
29
return
false;
30
}
31
$idcard
=
substr
(
$idcard
,0,6).
"19"
.
substr
(
$idcard
,6,9);
//15to18
32
$Bit18
= getVerifyBit(
$idcard
);
//算出第18位校驗碼
33
$idcard
=
$idcard
.
$Bit18
;
34
}
35
// 判斷是否大於2078年,小於1900年
36
$year
=
substr
(
$idcard
,6,4);
37
if
(
$year
<1900 ||
$year
>2078 )
38
{
39
return
false;
40
}
41
42
//18位身份證處理
43
$sBirthday
=
substr
(
$idcard
,6,4).
'-'
.
substr
(
$idcard
,10,2).
'-'
.
substr
(
$idcard
,12,2);
44
$d
=
new
DateTime(
$sBirthday
);
45
$dd
=
$d
->format(
'Y-m-d'
);
46
if
(
$sBirthday
!=
$dd
)
47
{
48
return
false;
49
}
50
//身份證編碼規范驗證
51
$idcard_base
=
substr
(
$idcard
,0,17);
52
if
(
strtoupper
(
substr
(
$idcard
,17,1)) != getVerifyBit(
$idcard_base
))
53
{
54
return
false;
55
}
56
return
$_POST
[
'idcard'
];
57
}
58
59
// 計算身份證校驗碼,根據國家標准GB 11643-1999
60
function
getVerifyBit(
$idcard_base
)
61
{
62
if
(
strlen
(
$idcard_base
) != 17)
63
{
64
return
false;
65
}
66
//加權因子
67
$factor
=
array
(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
68
//校驗碼對應值
69
$verify_number_list
=
array
(
'1'
,
'0'
,
'X'
,
'9'
,
'8'
,
'7'
,
'6'
,
'5'
,
'4'
,
'3'
,
'2'
);
70
$checksum
= 0;
71
for
(
$i
= 0;
$i
<
strlen
(
$idcard_base
);
$i
++)
72
{
73
$checksum
+=
substr
(
$idcard_base
,
$i
, 1) *
$factor
[
$i
];
74
}
75
$mod
=
$checksum
% 11;
76
$verify_number
=
$verify_number_list
[
$mod
];
77
return
$verify_number
;
78
}