《PHP實戰:PHP中快速生成隨機密碼的幾種方式》要點:
本文介紹了PHP實戰:PHP中快速生成隨機密碼的幾種方式,希望對您有用。如果有疑問,可以聯系我們。
PHP實戰思路是這樣的,密碼通常是英文字母和數字的混合編排,我們可以借助隨機函數rand函數隨機的選擇一個長字符串的一部分.
PHP實戰
function random_code($length = 8,$chars = null){
if(empty($chars)){
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
}
$count = strlen($chars) - 1;
$code = '';
while( strlen($code) < $length){
$code .= substr($chars,rand(0,$count),1);
}
return $code;
}
echo random_code;//A1zYbN5X
PHP實戰我們使用rand函數的目的是為了產生隨機的字符串,但是如果有一個函數可以做到的話,我們就沒有必要使用rand函數了.
PHP實戰
function random_char($length = 8,$chars = null){
if( empty($chars) ){
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
}
$chars = str_shuffle($chars);
$num = $length < strlen($chars) - 1 ? $length:str_len($chars) - 1;
return substr($chars,0,$num);
}
PHP實戰可以看到不使用rand函數,而是使用str_shuffle函數,好處是大大減少了代碼量.
PHP實戰更近一部的,我們的函數不僅可以生成隨機的密碼,還可以生成短信驗證碼,以及高強度的服務器登錄密碼.
PHP實戰
function random_code_type($length = 8,$type = 'alpha-number'){
$code_arr = array(
'alpha' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
'number'=> '0123456789',
'sign' => '#$%@*-_',
);
$type_arr = explode('-',$type);
foreach($type_arr as $t){
if( ! array_key_exists($t,$code_arr)){
trigger_error("Can not generate type ($t) code");
}
}
$chars = '';
foreach($type_arr as $t){
$chars .= $code_arr[$t];
}
$chars = str_shuffle($chars);
$number = $length > strlen($chars) - 1 ? strlen($chars) - 1:$length;
return substr($chars,0,$number);
}
echo random_code_type(8,"alpha-number-sign");#kXM*mC$S
PHP實戰以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持維易PHP.
轉載請注明本頁網址:
http://www.snjht.com/jiaocheng/958.html