我试图在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
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;
?>
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;
}