1. 程式人生 > >php 生成身份證號

php 生成身份證號

<?php /** * Created by PhpStorm. * User: 27394 * Date: 2017/3/15 * Time: 10:54 */ class idcard_gen{ protected $_debug = FALSE;//是否列印DEBUG資訊 protected $_idcard = '';//身份證號 protected $_end = FALSE; protected $pow = array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);//權重 protected $szVerCode = array
('1','0','X','9','8','7','6','5','4','3','2');//檢驗碼 protected static $_instance;// //防止使用者跳過單例模式 protected function __construct(){ } /* * 設定初始身份證號碼 **/ protected function init($idcard){ if (!$idcard) { if (!$this->_idcard) { $this->_idcard = '440982'
. date('Ymd' , rand(strtotime('1950-01-01') , time() - 10 * 86400 * 365)); } } else { $this->_idcard = $idcard; } } //將身份證後面四位作為一個整數加一 protected function idplus(){ $idcard = $this->_idcard; if (strlen($idcard) < 18) { $idcard
= str_pad($idcard , 18 , '0' , STR_PAD_RIGHT); } $last = substr($idcard , -4); $last++; if ($last > 9999) { $this->_end = TRUE; return; } $this->_idcard = substr($idcard , 0 , -4) . sprintf('%04d' , $last); } /* * 產生一個身份證 * @return string 身份證 **/ protected function do_gen(){ //窮舉直至演算法正確 do { $this->idplus(); if ($this->_end) return; if ($this->_debug) { echo 'checking: ' . $this->_idcard . " ...\n"; } $total = 0; for ($i = 0, $len = strlen($this->_idcard); $i < ($len-1) ; $i++) { $power = $this->_idcard[$i] * $this->pow[$i]; $total += $power; } $mod = $total % 11; }while(substr($this->_idcard , 17 , 1) != $this->szVerCode[$mod]); return $this->_idcard; } /* * 需要生成幾個身份證號碼 * @param int $num 需要生成身份證的個數 * @return array 身份證 **/ protected function multi_gen($num = 1){ $num = intval($num); if ($num < 1) exit('param is not valid'); $idcards = array(); for ($i = 0 ; $i < $num ; $i++) { if ($tmp = $this->do_gen()) { $idcards[] = $tmp; } if ($this->_end) break; } return $idcards; } /* * 需要生成幾個身份證號碼 * @param string $idcard 初始化身份證前面14位。如果不填,則系統自動生成一個。 * @param int $num 需要生成身份證的個數 * @return array 身份證 **/ public static function gen($num = 1 , $idcard = ''){ if (!self::$_instance) { self::$_instance = new self(); } self::$_instance->init($idcard); return self::$_instance->multi_gen($num); } } $cards = idcard_gen::gen(10); print_r($cards);