在php中生成随机密码 [英] Generating a random password in php
本文介绍了在php中生成随机密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在php中生成一个随机密码.
I am trying to generate a random password in php.
但是我得到的都是'a',返回类型是array类型,我希望它是一个字符串.有关如何更正代码的任何想法?
However I am getting all 'a's and the return type is of type array and I would like it to be a string. Any ideas on how to correct the code?
谢谢.
function randomPassword() {
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
for ($i = 0; $i < 8; $i++) {
$n = rand(0, count($alphabet)-1);
$pass[$i] = $alphabet[$n];
}
return $pass;
}
推荐答案
安全警告:
rand()
不是密码安全的伪随机数生成器.在其他地方查找在PHP中生成加密安全的伪随机字符串.
Security warning:
rand()
is not a cryptographically secure pseudorandom number generator. Look elsewhere for generating a cryptographically secure pseudorandom string in PHP.
尝试一下(使用strlen
而不是count
,因为字符串上的count
始终是1
):
Try this (use strlen
instead of count
, because count
on a string is always 1
):
function randomPassword() {
$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
return implode($pass); //turn the array into a string
}
演示: http://codepad.org/UL8k4aYK
这篇关于在php中生成随机密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文