php 密碼生成類
功能:
1.可設定密碼長度。
2.可設定要生成的密碼個數,批量生成。
3.可以指定密碼的規則,字母,數字,特殊字符等。
GeneratePassword.class.php
<?php
/** Generate Password class,根據指定規則生成password
* Date: 2013-12-23
* Author: fdipzone
* Ver: 1.0
*
* Func:
* public batchGenerate 批量生成密碼
* private generate 生成單個密碼
* private getLetter 獲取字母
* private getNumber 獲取數字
* private getSpecial 獲取特殊字符
*/
class GeneratePassword{ // class start
// 密碼的規則 default
private $_rule = array(
'letter' => 1,
'number' => 1,
'special' => 1
);
private $_length = 8; // 密碼長度
private $_num = 1; // 密碼數量
private $_special = '!@#$%^&*()_+=-'; //允許的特殊字符
/** 初始化
* @param int $length 密碼長度
* @param int $num 密碼數量
* @param Array $rule 密碼規則
* @param String $special 允許的特殊字符
*/
public function __construct($length=8, $num=1, $rule=array(), $special=''){
if(isset($length) && is_numeric($length) && $length>=4 && $length<=50){ // 長度
$this->_length = $length;
}
if(isset($num) && is_numeric($num) && $num>0 && $num<=100){ // 數量
$this->_num = $num;
}
if(isset($special) && is_string($special) && $special!=''){ // 特殊字符
$this->_special = $special;
}
if($rule){ // 規則
$t_rule = array();
if(isset($rule['letter']) && in_array($rule['letter'], array(1,2,3,4,5))){ // 1:可選用 2:必須 3:必須小寫 4:必須大寫 5:大小寫都必須
$t_rule['letter'] = $rule['letter'];
}
if(isset($rule['number']) && in_array($rule['number'], array(1,2))){ // 1:可選用 2:必須
$t_rule['number'] = $rule['number'];
}
if(isset($rule['special']) && in_array($rule['special'], array(1,2))){ // 1:可選用 2:必須
$t_rule['special'] = $rule['special'];
}
if($t_rule){
$this->_rule = $t_rule;
}
}
}
/** 批量生成密碼
* @return Array
*/
public function batchGenerate(){
$passwords = array();
for($i=0; $i<$this->_num; $i++){
array_push($passwords, $this->generate());
}
return $passwords;
}
/** 生成單個密碼
* @return String
查看本欄目