上传文件 PHP 时生成唯一文件名的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4371941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best method to generate unique filenames when uploading files PHP
提问by Adamski
Can any one suggest the best practice to generate unique file names for file uploads to avoid duplicate Entries?
任何人都可以建议为文件上传生成唯一文件名以避免重复条目的最佳做法吗?
Thanks In Advance.
提前致谢。
回答by ryudice
I usually either create a UID using uniqid() function for the filename or create a folder with the name of the username who is uploading the file and leave the original filename. The disadvantage of the first one is that you will have to save the original filename somewhere to show to the user.
我通常要么使用 uniqid() 函数为文件名创建一个 UID,要么创建一个带有上传文件的用户名的文件夹并保留原始文件名。第一个的缺点是您必须将原始文件名保存在某处以显示给用户。
回答by Kevin Stock
This function may help:
此功能可能有助于:
http://php.net/manual/en/function.uniqid.php
http://php.net/manual/en/function.uniqid.php
You may also consider looking into using a hash of the files contents such as:
您还可以考虑使用文件内容的哈希,例如:
回答by Colin O'Dell
You could use the unix timestamp of when the file was uploaded. If you expect several uploads to occur simultaneously, you could append a unique user ID or part of the original filename.
您可以使用文件上传时的 Unix 时间戳。如果您希望多个上传同时发生,您可以附加一个唯一的用户 ID 或原始文件名的一部分。
回答by cnizzardini
Something like this:
像这样的东西:
$filename = md5(date('Y-m-d H:i:s:u'));
Since MD5 hashes are not guaranteed to be unique, it's a good idea to check for collisions using file_exists($filename). In that case, rerun the above.
由于不能保证 MD5 哈希是唯一的,因此最好使用 file_exists($filename) 检查冲突。在这种情况下,重新运行上面的。
回答by EboMike
There's tempnam
and tmpfile
, if you want to create files, or this question.
有tempnam
和tmpfile
,如果你想创建文件,或者这个问题。
回答by Freddie
$username.$timestamp.$randomNumber
$username.$timestamp.$randomNumber
or you could hash this if you don't want people to know details of when it was uploaded and by whom
或者,如果您不希望人们知道上传时间和上传者的详细信息,则可以对其进行哈希处理