简体   繁体   English

在PHP中生成唯一ID

[英]Generating a unique ID in PHP

I'm trying to generate a unique ID in php in order to store user-uploaded content on a FS without conflicts. 我正在尝试在php中生成一个唯一的ID,以便将用户上传的内容存储在FS上而不会发生冲突。 I'm using php, and at the moment this little snippet is responsible for generating the UID: 我正在使用php,目前这个小片段负责生成UID:

$id = tempnam (".", "");
unlink($id);
$id = substr($id, 2);

This code is hideous: it creates a temporary file on the FS and deletes it, retaining only the relevant unique part of the generated string. 这段代码很可怕:它在FS上创建一个临时文件并删除它,只保留生成的字符串的相关唯一部分。

Is there any better way to do this, most preferably without any external dependencies? 有没有更好的方法来做到这一点,最好没有任何外部依赖?

Thanks much! 非常感谢!

string uniqid ([ string $prefix [, bool $more_entropy ]] )

根据当前时间(以微秒为单位)获取带前缀的唯一标识符。

USAGE: $id = uniqid(rand(), true);

Since both uniqid() and rand() are functions based on the current time, rand() adds almost no entropy, since the time will change only a tiny amount between the respective calls. 由于uniqid()和rand()都是基于当前时间的函数,因此rand()几乎不添加熵,因为时间在相应的调用之间只会改变很小的数量。

As long as you use the more_entropy option, you should never have a collision within a single server. 只要使用more_entropy选项,就不应该在单个服务器中发生冲突。 If you use clustering, be sure to include a prefix that differs between servers. 如果使用群集,请确保在服务器之间包含不同的前缀。

uniqid() is what you're looking for in most practical situations. uniqid()是你在大多数实际情况中寻找的东西。

You can make it even more "uniq" by adding a large random number after it. 您可以通过在其后面添加一个大的随机数使其更加“uniq”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM