我试图在PHP中创建一个随机字符串,我得到绝对没有输出:
<?php
function RandomString()
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randstring = '';
for ($i = 0; $i < 10; $i++) {
$randstring = $characters[rand(0, strlen($characters))];
}
return $randstring;
}
RandomString();
echo $randstring;
我做错了什么?
只使用PHP本地函数的参数化一行程序,从PHP 5.1.0开始工作
str_shuffle(implode('', (array_intersect_key(($map = array_map('chr', array_merge(array_map('mt_rand', array_fill(0, $length = 25, 48), array_fill(0,$length,57)),array_map('mt_rand', array_fill(0, $length, 65), array_fill(0,$length,90)),array_map('mt_rand', array_fill(0, $length, 97), array_fill(0,$length,122))))), array_flip($keys = array_rand($map, $length))))))
使用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