我试图在php中生成一个随机密码。
但是我得到的都是'a'返回类型是数组类型,我希望它是字符串。对如何修改代码有什么想法吗?
谢谢。
function randomPassword() {
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
for ($i = 0; $i < 8; $i++) {
$n = rand(0, count($alphabet)-1);
$pass[$i] = $alphabet[$n];
}
return $pass;
}
如果你在PHP7上,你可以使用random_int()函数:
function generate_password($length = 20){
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.
'0123456789`-=~!@#$%^&*()_+,./<>?;:[]{}\|';
$str = '';
$max = strlen($chars) - 1;
for ($i=0; $i < $length; $i++)
$str .= $chars[random_int(0, $max)];
return $str;
}
旧答案如下:
function generate_password($length = 20){
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.
'0123456789`-=~!@#$%^&*()_+,./<>?;:[]{}\|';
$str = '';
$max = strlen($chars) - 1;
for ($i=0; $i < $length; $i++)
$str .= $chars[mt_rand(0, $max)];
return $str;
}
试着用大写字母,小写字母,数字和特殊字符
function generatePassword($_len) {
$_alphaSmall = 'abcdefghijklmnopqrstuvwxyz'; // small letters
$_alphaCaps = strtoupper($_alphaSmall); // CAPITAL LETTERS
$_numerics = '1234567890'; // numerics
$_specialChars = '`~!@#$%^&*()-_=+]}[{;:,<.>/?\'"\|'; // Special Characters
$_container = $_alphaSmall.$_alphaCaps.$_numerics.$_specialChars; // Contains all characters
$password = ''; // will contain the desired pass
for($i = 0; $i < $_len; $i++) { // Loop till the length mentioned
$_rand = rand(0, strlen($_container) - 1); // Get Randomized Length
$password .= substr($_container, $_rand, 1); // returns part of the string [ high tensile strength ;) ]
}
return $password; // Returns the generated Pass
}
假设我们需要10位Pass
echo generatePassword(10);
示例输出:
IZCQ_IV \ 7
@wlqsfhT (d
是1!8 + 1 \ 4 @ud
有一个简短的解决方案(php 8.1):
$dict = array_merge(
...array_map(
fn(array $d): array => range(ord($d[0]), ord($d[1])),
[["0", "9"], ["a", "z"], ["A", "Z"]]
)
);
$f = fn (int $len): string =>
join(
"",
array_map(
fn (): string => chr($dict[random_int(0, count($dict) - 1)]),
range(0, $len)
)
);
echo $f(12) . PHP_EOL;
一行bash脚本:
PHP -r '$dict = array_merge(…到fn(数组$ d):数组= >范围(奥德($ d[0]),奥德($ d[1])),(“0”,“9”,“一个”、“z”,[“一”、“z”]]));$ f = fn (int len美元):字符串= >加入(“”,到(fn():字符串= >科($ dict [random_int (0, count ($ dict) - 1))),范围(0,len美元)));Echo $f(12)。PHP_EOL;”
这是来自https://stackoverflow.com/a/41077923/5599052的想法