【问题标题】:php Unique filename when uploadingphp 上传时唯一的文件名
【发布时间】:2012-01-23 17:43:14
【问题描述】:

我在我的网站上有一个带有图片上传的提交讨论表单。现在,我想在用户提交他们的图像时上传一个唯一的文件名,以便我可以显示所有图像的结果并避免重复的文件名。

我怎样才能用 php 做到这一点?如果您需要我的表单处理代码,我会上传。

【问题讨论】:

标签: php upload image-uploading


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    不确定您的代码究竟是什么样的,但您可以这样做:

    $filename = uniqid() . $orig_filename;
    

    Read this documentation on the PHP docs about uniqid for more information。它使用日期时间输出一个唯一的标识符字符串。

    【讨论】:

    • 对不起,你能给我举个例子吗
    • 嗯,就是把唯一ID的名字改成数据库,像这样:4eef63add36881162_03.JPG。但是在图片文件夹中显示的是原始图片名称,Like:1162_03.jpg,我可以将原始图片名称更改为数据库图片名称吗?
    • 我解决了这个问题。感谢您抽出时间来巴特金斯。
    • 一旦你得到了你想要的图片并且你得到了一个唯一的ID,你可以用那个唯一的ID重命名它。 $NewName = uniqid() 。 $orig_filename; rename('文件夹/' . $_FILES["PicUpload"]["name"], "folder/$NewName");
    【解决方案3】:

    如果你需要一个唯一的名字,你可以使用uniqid

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

    请注意,它仅在一台机器上是唯一的,即如果您在两台不同的机器上同时运行它,它可以生成相同的东西。

    【讨论】:

    • +1 for '请注意,它仅在一台机器上是唯一的,即如果你在两台不同的机器上同时运行它,它可以生成相同的东西。'
    【解决方案4】:

    IMO 的最佳选择是使用 sha1_file 它将根据文件内容创建一个唯一的哈希。这只会在其相同的图像或哈希冲突(这是 2^160 中的 1 概率)时发生冲突。您可以通过这种方式避免重复图像,但是因为您从文件中创建哈希可能会更慢。

    $filename = sha1_file($upload_file) . $ext;
    


    另一个选项是tempnam 它将创建一个具有唯一名称的临时文件。

    注意:如果 PHP 无法在指定的 dir 参数中创建文件,则回退到系统默认值。

    基本示例:

    $filename = tempnam($dir, $prefix);
    unlink($filename)//we don't need the tempfile just the name
    

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

    【讨论】:

      【解决方案5】:

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

      【讨论】:

      • 更好的方法是什么意思?我认为要么使用其他 cmets 中建议的 unique_id,要么使用用户名他们的文件是 2 种最佳方法?如果您计划向客户显示名称,那么更好的方法是允许用户使用用户友好的名称命名他们的文件,否则您将向客户显示可能不合适的 unique_id。
      猜你喜欢
      • 1970-01-01
      • 2016-01-08
      • 1970-01-01
      • 2011-05-21
      • 2016-08-28
      • 2013-03-09
      • 2010-10-02
      • 1970-01-01
      相关资源
      最近更新 更多