我试图在PHP中创建一个随机字符串,我得到绝对没有输出:
<?php
function RandomString()
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randstring = '';
for ($i = 0; $i < 10; $i++) {
$randstring = $characters[rand(0, strlen($characters))];
}
return $randstring;
}
RandomString();
echo $randstring;
我做错了什么?
我已经测试了那里最流行的函数的性能,在我的盒子上生成1 000 000个32个符号的字符串所需的时间是:
2.5 $s = substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,32);
1.9 $s = base64_encode(openssl_random_pseudo_bytes(24));
1.68 $s = bin2hex(openssl_random_pseudo_bytes(16));
0.63 $s = base64_encode(random_bytes(24));
0.62 $s = bin2hex(random_bytes(16));
0.37 $s = substr(md5(rand()), 0, 32);
0.37 $s = substr(md5(mt_rand()), 0, 32);
请注意,它到底有多长并不重要,重要的是哪个更慢,哪个更快,因此您可以根据您的要求进行选择,包括密码准备等。
如果需要小于32个字符的字符串,则在MD5周围添加substr()以保证准确性。
为了回答:字符串没有被连接,而是被覆盖,函数的结果没有被存储。
我想要特定字符和预设长度的伪随机字符串。我希望当前版本的PHP具有最高质量的伪随机性,此时它可以是v5、v6、v7或v8,并且可以使用默认配置或特殊配置。为了解决这种混乱,我在这里选取了其他几个答案,并包含了函数可用性条件。
使用。要全局使用它,给$VALID_ID_CHARS赋值你想要的字符,然后调用它:
$VALID_ID_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
$myNewRandomId = makeId(6);
function makeId($desiredLen)
{
global $VALID_ID_CHARS;
if ($desiredLen < 1) {
throw new \RangeException("Length must be a positive integer");
}
$vLen = 0;
if (function_exists('mb_strlen')) {
$vLen = mb_strlen($VALID_ID_CHARS, '8bit') - 1;
} else {
$vLen = strlen($VALID_ID_CHARS) - 1;
}
if (function_exists('random_int')) {
$pieces = [];
for ($i = 0; $i < $desiredLen; ++$i) {
$pieces[] = $VALID_ID_CHARS[random_int(0, $vLen)];
}
return implode('', $pieces);
}
if (function_exists('openssl_random_pseudo_bytes')) {
$random = openssl_random_pseudo_bytes($desiredLen);
$id = '';
for ($i = 0; $i < $desiredLen; ++$i) {
$id .= $VALID_ID_CHARS[ord($random[$i]) % $vLen];
}
return $id;
}
http_response_code(500);
die('random id generation failed. either random_int or openssl_random_pseudo_bytes is needed');
}
使用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