【发布时间】:2012-05-20 11:21:20
【问题描述】:
此代码是我计划用于生成门票唯一代码的代码。
// A prefix to avoid uniqid collisions (when invoking this function at the same time).
// Should I use mt_rand or just rand?
$prefix = str_pad(dechex(mt_rand(0, 0xFFFFFF)), 6, '0', STR_PAD_LEFT);
// uniqid with more entropy enabled.
$unique_id = uniqid("$prefix-", TRUE);
// A SHA-1 hash for the generated code, this way it looks less sequential.
$unique_id = sha1($unique_id);
如果你能告诉我这段代码中的问题会更有帮助。
提前致谢。
【问题讨论】:
-
Afaik 你不需要添加前缀来避免冲突。为什么?因为您也可以在前缀中发生冲突!
uniqid()发生碰撞的可能性已经很低,您无需担心。此外,通过使用哈希函数(将无限集映射到有限集)对其进行哈希处理,您会引入很高的冲突机会。 -
补充:我可能需要纠正一下自己。显然,多个主机仍然可以在同一微秒内产生相同的
uniqid。但是你可以只使用主机名作为前缀。
标签: php code-generation sha1