我有一个提交讨论表单与图像上传在我的网站。现在,我想在用户提交图像时上传一个唯一的文件名,这样我就可以显示所有图像的结果,并避免重复的文件名。
如何在php中做到这一点?如果你需要我的表单处理代码,我可以上传它
可以使用uniqid()
函数生成唯一的ID
/**
* Generate a unique ID
* @link http://www.php.net/manual/en/function.uniqid.php
* @param prefix string[optional] <p>
* Can be useful, for instance, if you generate identifiers
* simultaneously on several hosts that might happen to generate the
* identifier at the same microsecond.
* </p>
* <p>
* With an empty prefix, the returned string will
* be 13 characters long. If more_entropy is
* true, it will be 23 characters.
* </p>
* @param more_entropy bool[optional] <p>
* If set to true, uniqid will add additional
* entropy (using the combined linear congruential generator) at the end
* of the return value, which should make the results more unique.
* </p>
* @return string the unique identifier, as a string.
*/
function uniqid ($prefix = null, $more_entropy = null) {}
您可以在日期中使用时间戳,这样您就不会两次获得相同的文件名/时间。
不确定你的代码是什么样子的,但是你可以这样做:
$filename = uniqid() . $orig_filename;
阅读关于uniqid的PHP文档以获取更多信息。它使用日期时间输出一个唯一标识符字符串。
如果您需要一个唯一的名称,您可以使用uniqid
$filename = uniqid() . '.jpeg';
请注意,它只能在一台机器上是唯一的,也就是说,如果你在两台不同的机器上同时运行它,它可以生成相同的东西
我认为最好的选择是使用sha1_file,它将根据文件内容创建一个唯一的哈希。这只会发生碰撞,如果是相同的图像或者哈希碰撞,概率是1/2^160。你可以避免重复的图像,但是,因为你是从文件创建一个哈希,它可能会更慢。
$filename = sha1_file($upload_file) . $ext;
另一个选项是tempnam它将创建一个具有唯一名称的临时文件。
注意:如果PHP不能在指定的dir参数中创建文件,它将返回系统默认值
基本例子:
$filename = tempnam($dir, $prefix);
unlink($filename)//we don't need the tempfile just the name
另请注意:如果您更改文件名,它可能不是唯一的
我认为最简单的方法是将图像名称存储在数据库字段中,然后当用户上传他们的图像时,通过对现有文件名进行检查来验证文件名是否唯一。如果您不希望用户必须等到表单提交后才得到错误或提示更改文件名,则可以使用ajax/jquery接口。