我试图在PHP中创建一个随机字符串,我得到绝对没有输出:

<?php
    function RandomString()
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randstring = '';
        for ($i = 0; $i < 10; $i++) {
            $randstring = $characters[rand(0, strlen($characters))];
        }
        return $randstring;
    }

    RandomString();
    echo $randstring;

我做错了什么?


当前回答

function gen_uid($l=5){
   return substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"), 10, $l);
}
echo gen_uid();

默认值[5]:WvPJz

echo gen_uid(30);

价值[30]:cAiGgtf1lDpFWoVwjykNKXxv6SC4Q2

其他回答

只使用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))))))

你完全做错了,因为你依赖于数字,而不是字符,我不确定如果你想要随机输出只是数字,如果是这样,为什么需要得到所有的字母和所有的数字,并提取它们的长度?为什么不用rand(0,62)呢?,即使你在声明函数之前忘记初始化变量$randstring。

不管怎样,PHP为此目的提供了一个非常方便的函数。它的作用是()。下面是一个适合您需要的例子。

< ?php 函数随机字符串(){ $字符= '0123456789abcdefghijklmnopqrstuvwxyz '; 返回str_shuffle($字符); } echo randomString ();

使用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

最后,我找到了一个解决方案,以获得随机和唯一的值。

我的解决方案是:

substr(md5(time()), 0, 12)

Time总是返回一个时间戳,并且总是唯一的。您可以将其与MD5一起使用以使其更好。

function generateRandomString($length = 15)
{
    return substr(sha1(rand()), 0, $length);
}

哒哒!