我试图在PHP中创建一个随机字符串,我得到绝对没有输出:
<?php
function RandomString()
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randstring = '';
for ($i = 0; $i < 10; $i++) {
$randstring = $characters[rand(0, strlen($characters))];
}
return $randstring;
}
RandomString();
echo $randstring;
我做错了什么?
下面的函数生成任意长度的伪字符串。
/**
* Returns random string of a given length.
*/
function get_random_string($length) {
$pull = [];
while (count($pull) < $length) {
$pull = array_merge($pull, range(0, 9), range('a', 'z'), range('A', 'Z'));
}
shuffle($pull);
return substr(implode($pull), 0, $length);
}
我想要特定字符和预设长度的伪随机字符串。我希望当前版本的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 random($len){
$char = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
// ----------------------------------------------
// Number of possible combinations
// ----------------------------------------------
$pos = strlen($char);
$pos = pow($pos, $len);
echo $pos.'<br>';
// ----------------------------------------------
$total = strlen($char)-1;
$text = "";
for ($i=0; $i<$len; $i++){
$text = $text.$char[rand(0, $total)];
}
return $text;
}
$string = random(15);
echo $string;
?>
您也可以准时使用md5,但要小心。
您需要使用microtime()而不是time()函数,因为如果多个线程在同一秒内运行,则需要为所有线程获取不同的字符串。
<?php
$string = md5(microtime());
echo $string;
?>