简体   繁体   中英

Best way to give a file an unique name with php

I was wondering, without using any kind of user info (id, nickname, age, etc) , what would be the best way to assure filename uniqueness using php in a large database with high traffic and most probably simultaneously between many users? I am using $file = time() for example but I would like to know if this should suffice whenever two users might go over this code at the same time (at a large large large scale, 10000 users at the same time and the same function ran 200 times simultaneously).

time is not sufficiently unique, all it takes to get clashes is that line being ran twice in the same second.

This is what tempnam and tmpfile are meant for.

Despite the name, you can use tempnam to create files outside of the systems temporary directory, so they will be permanent.

Files created using tmpfile are temporary and are removed at the end of the program at the latest.

Is the file temporary? Then maybe tempnam . Or maybe look at uniqid .

Name your files based on the ID that the associated database record has. Your database guarantees uniqueness of this ID automatically. There is no need to re-invent the wheel.

除了使用db行插入ID之外,还应在文件名中使用当前时间戳(也许要附加microtime)。

除了仅命名文件的上下文之外,我使用以下调用来生成随机字符串以用于电子邮件确认哈希等,但是也可以在您的情况下使用。

$random = bin2hex(mcrypt_create_iv(4, MCRYPT_DEV_URANDOM));

以下是我通常用于随机字符串的内容,然后可以根据需要在文件末尾附加文件类型

sha1(uniqid(mt_rand(), TRUE));

How about microtime() ? It's like time() on steroids.

http://www.php.net/manual/en/function.microtime.php

同时使用时间戳和IP地址。

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