简体   繁体   中英

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. 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!

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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