php 上传时的唯一文件名
我的网站上有一个提交讨论表格,其中包含图像上传。现在,我想在用户提交图像时上传唯一的文件名,以便我可以显示所有图像的结果并避免重复的文件名。
我怎样才能用 php 做到这一点?如果您需要我的表单处理代码,我会上传它。
I've a submit discussion form with image upload in my website. Now, I want to upload a unique file name when the user submits their image so that I can show the result of all images and can avoid duplicate file names.
How can I do this with php? If you need my form process code then I'll upload it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用
uniqid()
函数生成唯一IDYou can use the
uniqid()
function to generate a unique ID您可以在日期中使用时间戳,这样您就不会两次获得相同的文件名/时间。
不确定你的代码到底是什么样子,但你可以这样做:
阅读有关 uniqid 的 PHP 文档更多信息。它使用日期时间输出唯一标识符字符串。
You could use a timestamp in the date, that way you won't get the same filename/time twice.
Not certain exactly what your code looks like but you could do something like this:
Read this documentation on the PHP docs about uniqid for more information. It uses the datetime to output a unique identifier string.
如果需要唯一的名称,可以使用
uniqid
。但请注意,它仅在一台机器上是唯一的,即如果您同时在两台不同的机器上运行它,它可以生成相同的东西。
If you need a unique name, you can use
uniqid
.Be warned though that it will only be unique across one machine, ie it can generate the same thing if you run it at the very same time on two different machines.
IMO 的最佳选择是使用 sha1_file 它将创建一个独特的基于文件内容的哈希值。只有在相同图像或哈希冲突(概率为 2^160 中为 1)时才会发生冲突。您可以通过这种方式避免重复图像,但是因为您是从文件创建哈希,所以速度可能会较慢。
另一个选项是tempnam它将创建一个具有唯一名称。
基本示例:
另请注意:如果更改文件名,它可能不是唯一的。
The best option IMO would be to to use sha1_file It will create a unique hash based on the file contents. This would only collide if its the same image or a hash collision which is a 1 in 2^160 chance. You can avoid having duplicate images this way however because you are creating a hash from the file it can be slower.
Another option is tempnam It will create a temp file with a unique name.
Basic example:
Also note: If you change the filename it might not be unique.
我认为最简单的方法是将图像名称存储在数据库字段中,然后当用户上传图像时,通过对照现有文件名检查文件名来验证文件名是否唯一。如果您不希望用户必须等到表单提交后才收到错误或提示更改文件名,您可以使用 ajax / jquery 界面。
I think the simplest way would be to store the image name in a database field and then when the user is uploading their image to validate that the file name is unique by checking it against existing filenames. You can use an ajax / jquery interface if you don't want the user to have to wait til the form has been submitted to get an error or prompt to change their filename.