提供一個靈活的 PHP 函數 genPassword(),可生成指定長度範圍的隨機密碼,預設使用小寫字母與數字,易於擴充字元集。
<?php
/**
* 生成隨機密碼
* @param int $min 最小長度(預設 5)
* @param int $max 最大長度(預設 8)
* @param string $chars 可用字元集(預設小寫字母+數字)
* @return string 隨機密碼
*/
function genPassword($min = 5, $max = 8, $chars = 'abcdefghijklmnopqrstuvwxyz123456789') {
$length = mt_rand($min, $max);
$maxIndex = strlen($chars) - 1;
$password = '';
for ($i = 0; $i < $length; $i++) {
$password .= $chars[mt_rand(0, $maxIndex)];
}
return $password;
}
// 使用範例
echo "預設密碼(5-8位):" . genPassword() . "<br>";
echo "自訂長度(5-10位):" . genPassword(5, 10) . "<br>";
echo "高強度密碼(含特殊符號):" . genPassword(12, 16, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*') . "<br>";
<?php
function genSecurePassword($level = 'medium', $length = 0) {
$charsets = array(
'low' => 'abcdefghijklmnopqrstuvwxyz0123456789', // 36 字元
'medium' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', // 62 字元
'high' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+[]{}|;:,.<>?', // 90+ 字元
);
$length = $length ?: array('low'=>8, 'medium'=>12, 'high'=>16)[$level];
$chars = $charsets[$level];
$maxIndex = strlen($chars) - 1;
$password = '';
for ($i = 0; $i < $length; $i++) {
$password .= $chars[mt_rand(0, $maxIndex)];
}
return $password;
}
// 使用範例
echo "低強度:" . genSecurePassword('low') . "<br>";
echo "中強度:" . genSecurePassword('medium') . "<br>";
echo "高強度:" . genSecurePassword('high') . "<br>";
echo "自訂長度高強度:" . genSecurePassword('high', 20) . "<br>";
random_int() 替代 mt_rand()0, O, o, 1, l, I 等易混淆字元password_hash() 儲存,切勿明文保存<?php
function genPasswordSecure($min = 12, $max = 16, $excludeAmbiguous = true) {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*';
if ($excludeAmbiguous) {
$chars = str_replace(array('0','O','o','1','l','I'), '', $chars);
}
$length = random_int($min, $max);
$maxIndex = strlen($chars) - 1;
$password = '';
for ($i = 0; $i < $length; $i++) {
$password .= $chars[random_int(0, $maxIndex)];
}
return $password;
}
此函數簡單易用,可直接整合至註冊、重設密碼、API Token 生成等場景,滿足不同安全等級需求。