verifyidcard.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. function verifyIdCard($idCard) {
  3. $flag = false;
  4. $regIdCard = '/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/';
  5. if (preg_match($regIdCard, $idCard)) {
  6. if (strlen($idCard) == 18) {
  7. $idCardWi = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
  8. $idCardY = array(1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2);
  9. $idCardWiSum = 0;
  10. for ($i = 0; $i < 17; $i++) {
  11. $idCardWiSum += intval(substr($idCard, $i, 1)) * $idCardWi[$i];
  12. }
  13. $idCardMod = $idCardWiSum % 11;
  14. $idCardLast = strtoupper(substr($idCard, 17));
  15. if ($idCardMod == 2) {
  16. if ($idCardLast == 'X') {
  17. $flag = true;
  18. } else {
  19. echo json_encode(array('code' => -2, 'msg' => '身份证最后一位输入错误'));
  20. exit;
  21. }
  22. } else {
  23. if ($idCardLast == $idCardY[$idCardMod]) {
  24. $flag = true;
  25. } else {
  26. echo json_encode(array('code' => -2, 'msg' => '身份证信息不正确'));
  27. exit;
  28. }
  29. }
  30. } else if (strlen($idCard) == 15) {
  31. $id17 = substr($idCard, 0, 6) . '19' . substr($idCard, 6);
  32. $parityBit = getParityBit($id17);
  33. $tempIdCard = $id17 . $parityBit;
  34. $flag = validateIdCard($tempIdCard);
  35. }
  36. } else {
  37. echo json_encode(array('code' => -2, 'msg' => '身份证号码有误,请重新输入'));
  38. exit;
  39. }
  40. return $flag;
  41. }