Including the conversion of 15-digit mainland ID number to 18-digit, ID number validity check and ID card information extraction.
- use DateTime;
- /**
- * ID card number processing class
- * @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());
- /**
- * Verify the validity of the ID number
- * @param string $idnum ID number
- * @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;
- }
-
- /**
- * Get ID card information
- * @param string $idnum ID number
- * @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 ? 'Male' : 'Female'
- );
- $datetime = new DateTime($data['birthday']);
- $data['age'] = $datetime->diff(date_create())->format('%y');
- return $this ->info(true, null, $data);
- }
-
- /**
- * 15-digit number upgraded to 18 digits
- * @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));
- }
-
- /**
- * Get confirmation code
- * @param string $idnum ID number
- * @return string Return confirmation code if successful, false if failed
- */
- 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)){
- $this->info = array_merge($info, $status);
- }elseif(is_bool($status) ){
- $info['status'] = $status;
- }
- return $this->info;
- }
-
- }
Copy code
|