php產生隨機密碼一些方法總結_PHP教程

來源:互聯網
上載者:User
當你想產生一個隨機的密碼的時候,你第一想到的可能是使用 uniquid() 函數,但是如果我們使用 array_rand() 和 range() ,可以更完美的實現這個功能。


方法一,

代碼如下 複製代碼

header("Content-type: text/html; charset=utf-8");

function randCode($length) {
$ranges = array(range('a', 'z'), range('A', 'Z'), range(1, 9));
$code = '';
for($i = 0; $i < $length; $i++){
$rkey = array_rand($ranges);
$vkey = array_rand($ranges[$rkey]);
$code .= $ranges[$rkey][$vkey];
}
return $code;
}

echo "www.bKjia.c0m";
echo randCode(5); // 輸出如:3IxY8、E6HOv、1qHiy等等
?>

方法二,

1、在 33 – 126 中產生一個隨機整數,如 35,

2、將 35 轉換成對應的ASCII碼字元,如 35 對應 #

3、重複以上 1、2 步驟 n 次,串連成 n 位的密碼

該演算法主要用到了兩個函數,mt_rand ( int $min , int $max )函數用於產生隨機整數,其中 $min – $max 為 ASCII 碼的範圍,這裡取 33 -126 ,可以根據需要調整範圍,如ASCII碼錶中 97 – 122 位對應 a – z 的英文字母,具體可參考 ASCII碼錶; chr ( int $ascii )函數用於將對應整數 $ascii 轉換成對應的字元。

代碼如下 複製代碼

function create_password($pw_length = 8)

{

$randpwd = '';

for ($i = 0; $i < $pw_length; $i++)

{

$randpwd .= chr(mt_rand(33, 126));

}

return $randpwd;

}

// 調用該函數,傳遞長度參數$pw_length = 6

echo create_password(6);

方法三,

代碼如下 複製代碼

//自動為使用者隨機產生使用者名稱(長度6-13)

function create_password($pw_length = 4){

$randpwd = '';

for ($i = 0; $i < $pw_length; $i++){

$randpwd .= chr(mt_rand(33, 126));

}

return $randpwd;

}

function generate_username( $length = 6 ) {

// 密碼字元集,可任意添加你需要的字元

$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_ []{}<>~`+=,.;:/?|';

$password = '';

for ( $i = 0; $i < $length; $i++ )

{

// 這裡提供兩種字元擷取方式

// 第一種是使用substr 截取$chars中的任意一位字元;

// 第二種是取字元數組$chars 的任意元素

// $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);

$password .= $chars[ mt_rand(0, strlen($chars) - 1) ];

}

return $password;

}

// 調用該函數

$userId = 'user'.generate_username(6);

$pwd = create_password(9);

http://www.bkjia.com/PHPjc/628618.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/628618.htmlTechArticle當你想產生一個隨機的密碼的時候,你第一想到的可能是使用 uniquid() 函數,但是如果我們使用 array_rand() 和 range() ,可以更完美的實現這個...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.