php上传时的唯一文件名

时间:2011-12-19 16:01:44

标签: php

我在我的网站上有一个提交图片上传的讨论表格。现在,我想在用户提交图像时上传唯一的文件名,以便我可以显示所有图像的结果,并且可以避免重复的文件名。怎么用PHP做到这一点?如果您需要我的表单流程代码,那么我将上传它。

非常感谢。

5 个答案:

答案 0 :(得分:10)

您可以使用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) {}

答案 1 :(得分:8)

您可以在日期中使用时间戳,这样您就不会获得两次相同的文件名/时间。

不确定您的代码究竟是什么样的,但您可以执行以下操作:

$filename = uniqid() . $orig_filename;

Read this documentation on the PHP docs about uniqid for more information。它使用datetime输出唯一标识符字符串。

答案 2 :(得分:3)

如果您需要唯一名称,可以使用uniqid

$filename = uniqid() . '.jpeg';

请注意,它只能在一台机器上保持唯一,即如果您在两台不同的机器上同时运行它,它可以产生相同的效果。

答案 3 :(得分:1)

IMO的最佳选择是使用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

另请注意:如果更改文件名,则可能不是唯一的。

答案 4 :(得分:0)

我认为最简单的方法是将图像名称存储在数据库字段中,然后在用户上传图像时通过检查现有文件名来验证文件名是否唯一。如果您不希望用户必须等到提交表单以获取错误或提示更改其文件名,您可以使用ajax / jquery接口。