我试图在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具有最高质量的伪随机性,此时它可以是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');
}
在PHP中生成随机字符串的另一种方法是:
function RandomString($length) {
$original_string = array_merge(range(0,9), range('a','z'), range('A', 'Z'));
$original_string = implode("", $original_string);
return substr(str_shuffle($original_string), 0, $length);
}
echo RandomString(6);
function randomName($length = 8) {
$values = array_merge(range(65, 90), range(97, 122), range(48, 57));
$max = count($values) - 1;
$str = chr(mt_rand(97, 122));
for ($i = 1; $i < $length; $i++) {
$str .= chr($values[mt_rand(0, $max)]);
}
return $str;
}