包含大陆身份证号15位转18位、身份号有效性检查以及身份证信息提取。 1. [代码] [PHP]代码 ?phpuse DateTime;/** * 身份证号处理类 * @author WeakSun 52132522@qq.com */class Idcard {static private $factor = a
1. [代码][PHP]代码
<?php use DateTime; /** * 身份证号处理类 * @author WeakSun <52132522@qq.com> */ class Idcard { static private $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2), $verify = array(1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2), $info = array('status' => false, 'info' => '', 'data' => array()); /** * 验证身份证号码有效性 * @param string $idnum 身份证号码 * @return array */ public function index($idnum = null) { switch (strlen($idnum)) { case 18: break; case 15: $idnum = $this->upgrade($idnum); break; default : return $this->info(false, 'error', $idnum); } $info = $this->getInfo($idnum); $info['status'] = $this->getCode($idnum) == strtoupper(substr($idnum, -1)); return $info; } /** * 获取身份证信息 * @param string $idnum 身份证号码 * @return array */ public function getInfo($idnum) { $data = array( 'id' => $idnum, 'city' => substr($idnum, 0, 6), 'birthday' => substr($idnum, 6, 4) . '-' . substr($idnum, 10, 2) . '-' . substr($idnum, 10, 2), 'sex' => substr($idnum, -2, 1) % 2 ? '男' : '女' ); $datetime = new DateTime($data['birthday']); $data['age'] = $datetime->diff(date_create())->format('%y'); return $this->info(true, null, $data); } /** * 15位号码升级18位 * @param string $idnum * @return array */ public function upgrade($idnum) { if (strlen($idnum) != 15) { $this->info(true, null, $idnum); } else { $idnum = array(substr($idnum, 0, 6), 19, substr($idnum, 6)); substr($idnum, -3) > 995 && $idnum[1] --; $idnum = implode('', $idnum); } return $this->info(true, null, $idnum . $this->getCode($idnum)); } /** * 获取确认码 * @param string $idnum 身份证号码 * @return string 成功返回确认码,失败返回false */ protected function getCode($idnum) { $code = 0; foreach (str_split($idnum) as $k => $v) { $code += $v * static::$factor[$k]; } $index = $code % 11; return static::$verify[$index]; } protected function info($status, $msg = null, $data = null) { $info = static::$info; empty($msg) || $info['info'] = $msg; empty($data) || $info['data'] = $data; if(is_array($status)){ $info = array_merge($info, $status); }elseif(is_bool($status)){ $info['status'] = $status; } return $info; } }