Laravel str_random()函数是否足够随机,以便我可以将它用于ID?
例如:
str_random(32);
这会产生一个长度为32的随机字符串,由字母数字字符组成[a-zA-z0-9](共62个字符)。
这相当于2272657884496751345355241563627544170162852933518655225856可能性。
然而,我的问题是,这是否足够好?或者我应该考虑使用UUID还是其他自定义函数。
答案 0 :(得分:50)
str_random
(Str::random()
)尝试使用openssl_random_pseudo_bytes
,这是一个针对加密而非唯一性优化的伪随机数生成器。如果openssl_random_pseudo_bytes
不可用,则会回退到quickRandom()
:
public static function quickRandom($length = 16)
{
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
return substr(str_shuffle(str_repeat($pool, 5)), 0, $length);
}
在我看来,quickRandom
代码对于唯一性和加密不是可靠。
是的,拥有openssl_random_pseudo_bytes
并使用32个字节几乎不可能看到碰撞,但它仍然可能。如果你想确保你的字符串/数字是唯一的(99.99%),你最好使用UUID函数。这就是我通常使用的:
/**
*
* Generate v4 UUID
*
* Version 4 UUIDs are pseudo-random.
*/
public static function v4()
{
return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
// 32 bits for "time_low"
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
// 16 bits for "time_mid"
mt_rand(0, 0xffff),
// 16 bits for "time_hi_and_version",
// four most significant bits holds version number 4
mt_rand(0, 0x0fff) | 0x4000,
// 16 bits, 8 bits for "clk_seq_hi_res",
// 8 bits for "clk_seq_low",
// two most significant bits holds zero and one for variant DCE1.1
mt_rand(0, 0x3fff) | 0x8000,
// 48 bits for "node"
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
它生成一个VALID RFC 4211 COMPLIANT版本4 UUID。
请检查:http://en.wikipedia.org/wiki/UUID#Random%5FUUID%5Fprobability%5Fof%5Fduplicates
答案 1 :(得分:2)
您可以使用
use Illuminate\Support\Str;
$random = Str::random(40);
答案 2 :(得分:1)
答案 3 :(得分:1)
2014年4月接受的答案是正确的,现在不再准确。 2014年11月,there was a commit删除了quickRandom
的使用。随着random_bytes
在PHP 7中可用,Laravel逐渐转变为使用该函数,并且仅使用该函数而没有任何后备。
Laravel中的默认UUID库为ramsey/uuid
。通过查看代码,我们可以发现默认的随机生成器是RandomBytesGenerator
,它使用random_bytes
的方式与Str::random
所使用的方法相同。
有关UUID的Wikipedia页面陈述了有关UUID v4的以下内容:
[...]版本4 UUID将具有6个预定的变体和版本位,为随机生成的部分保留122位,[...]
https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_(random)
128位= 122个随机位+ 6个版本位。 128位正好是16个字节。大多数UUID实现都会读取16个字节的随机字节,然后在指定位置(对于v4)替换版本。
总而言之,到目前为止,如果您使用长度等于16或Str::random
的{{1}}(无需对Uuid::uuid4
的{{1}}进行任何修改,则几乎相同) )。
答案 4 :(得分:0)
我使用的是 Laravel 6 版本,在 Illuminate\Support\Str::random 上运行良好,但是 str_random 和 Illuminate\Support\Str::str_random 都不适用于我使用 Laravel 6。
下面你可以看到函数的文档
http://192.168.3.7/geoportal-service/info
答案 5 :(得分:0)
为了使它更独特,使用 TIMESTAMP 和 concat 行 id,简单且重复数字的可能性为零