核心函數
function getRandPass($length = 6) {
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$password = '';
$max = strlen($chars) - 1;
for ($i = 0; $i < $length; $i++) {
$password .= $chars[mt_rand(0, $max)];
}
return $password;
}
echo getRandPass(12); // 12位隨機密碼
安全加強版(PHP 7+)
function getSecurePass($length = 16) {
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*';
$bytes = random_bytes($length);
$password = '';
for ($i = 0; $i < $length; $i++) {
$password .= $chars[$bytes[$i] % strlen($chars)];
}
return $password;
}
- 使用
random_bytes() (CSPRNG) 替代 mt_rand(),密碼學安全。
- 字符集加入特殊符號提高熵值。
使用建議
- 用戶註冊初始密碼、API Token、臨時訪問碼等場景。
- 生成後務必**安全存儲**(BCrypt/Argon2 哈希),不可明文日誌/郵件發送。