Generating a unique ID in PHP

允我心安 提交于 2019-12-20 11:56:37

问题


I'm trying to generate a unique ID in php in order to store user-uploaded content on a FS without conflicts. I'm using php, and at the moment this little snippet is responsible for generating the 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.

Is there any better way to do this, most preferably without any external dependencies?

Thanks much!


回答1:


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

Gets a prefixed unique identifier based on the current time in microseconds.

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



回答2:


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.

As long as you use the more_entropy option, you should never have a collision within a single server. If you use clustering, be sure to include a prefix that differs between servers.




回答3:


uniqid() is what you're looking for in most practical situations.

You can make it even more "uniq" by adding a large random number after it.



来源:https://stackoverflow.com/questions/181159/generating-a-unique-id-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!