本文整理四款 PHP 隨機密碼產生函式,涵蓋自訂字元集、固定長度數字字母混合、ASCII 碼範圍、效能測試等不同需求。
function generate_password($length = 8) { // 密碼字元集,可自行增減符號 $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_ []{}<>~`+=,.;:/?|'; $password = ''; for ($i = 0; $i < $length; $i++) { // 使用 mt_rand() 取得較佳隨機性 $password .= $chars[mt_rand(0, strlen($chars) - 1)]; } return $password; } // 使用範例 echo generate_password(12); // 產生 12 位密碼
<?php // 純數字字母 6 碼 $str = "0123456789abcdefghijklmnopqrstuvwxyz"; $n = 6; $len = strlen($str) - 1; for ($j = 0; $j < 200; $j++) { // 批次產生 200 組 $s = ''; for ($i = 0; $i < $n; $i++) { $s .= $str[rand(0, $len)]; } echo $s . "<br/>"; } // 包含符號的固定比例密碼 $a = "12345678"; $b = "abcdefghijklmnopqistuvwxyz"; $s = substr(str_shuffle($a), 0, 2); // 2 位數字 $e = substr(str_shuffle($b), 0, 2); // 2 位字母 echo $s . substr(str_shuffle("!@#$%^&*"), 0, 2) . $e; // 2 位符號
function create_password($pw_length = 8) { $randpwd = ''; for ($i = 0; $i < $pw_length; $i++) { // ASCII 33-126 為可列印字元 $randpwd .= chr(mt_rand(33, 126)); } return $randpwd; } echo create_password(6); // 產生 6 位含符號密碼
<?php function getmicrotime() { list($usec, $sec) = explode(" ", microtime()); return ((float)$usec + (float)$sec); } $time_start = getmicrotime(); // 這裡放入要測試的程式碼 // echo create_password(6); $time_end = getmicrotime(); $time = $time_end - $time_start; echo "執行時間 $time seconds"; ?>
random_bytes() 或 random_int() 取代 mt_rand()/rand()password_hash()