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)
);
}
它会生成一个有效的 RFC 4211 COMPLIANT 版本 4 UUID。
检查这个:https://en.wikipedia.org/wiki/Universally_unique_identifier#Collisions