我试图在PHP中创建一个随机字符串,我得到绝对没有输出:
<?php
function RandomString()
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randstring = '';
for ($i = 0; $i < 10; $i++) {
$randstring = $characters[rand(0, strlen($characters))];
}
return $randstring;
}
RandomString();
echo $randstring;
我做错了什么?
使用random_bytes函数生成加密安全的随机字节。
$bytes = random_bytes(16);
echo bin2hex($bytes);
可能的输出
da821217e61e33ed4b2dd96f8439056c
使用openssl_random_pseudo_bytes函数生成伪随机字节。
$bytes = openssl_random_pseudo_bytes(16);
echo bin2hex($bytes);
可能的输出
e2d1254506fbb6cd842cd640333214ad
最好的用例是
function getRandomBytes($length = 16)
{
if (function_exists('random_bytes')) {
$bytes = random_bytes($length / 2);
} else {
$bytes = openssl_random_pseudo_bytes($length / 2);
}
return bin2hex($bytes);
}
echo getRandomBytes();
可能的输出
ba8cc342bdf91143
具体回答这个问题,有两个问题:
当你回显$randstring时,它不在作用域内。
字符在循环中没有连接在一起。
以下是更正后的代码片段:
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[random_int(0, $charactersLength - 1)];
}
return $randomString;
}
用下面的调用输出随机字符串:
// Echo the random string.
// Optionally, you can give it a desired string length.
echo generateRandomString();
请注意,这个答案的以前版本使用rand()而不是random_int(),因此生成可预测的随机字符串。因此,根据这个答案的建议,它被更改为更安全。