首页 > PHP教程 > php开发知识文章

PHP 生成随机密码的方法 -- rand,str_shuffle

本文主要介绍了PHP 生成随机密码的方法,欢迎大家的学习。

web网站的用户密码一般为英文字母和数字或特殊符号的组合的,使用随机函数rand()随机选择一个长字符串的一部分。

使用rand()函数

使用rand函数是为了产生随机的字符串。

function rand_re($length = 6, $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 rand_re();

使用str_shuffle函数

function rand_char($length = 6, $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);
}

生成多种类的代码

函数生成随机的密码,生成短信验证码,及高强度的其他密码。

function rand_code($length = 6, $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 rand_code(6, "alpha-number-sign");

以上就是本文PHP 生成随机密码的方法的全部内容,希望对大家的学习有所帮助。

关闭
感谢您的支持,我会继续努力!
扫码打赏,建议金额1-10元


提醒:打赏金额将直接进入对方账号,无法退款,请您谨慎操作。