[php上载时的唯一文件名

问题描述 投票:8回答:5

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

我该如何使用php?如果您需要我的表单处理代码,则将其上传。

php upload image-uploading
5个回答
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) {}

9
投票

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

不确定代码的外观,但可以执行以下操作:

$filename = uniqid() . $orig_filename;

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


3
投票

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

uniqid

尽管请注意,它将仅在一台计算机上唯一,即,如果您同时在两台不同的计算机上运行它,则它可以生成相同的事物。


1
投票

IMO的最佳选择是使用$filename = uniqid() . '.jpeg'; ,它将基于文件内容创建唯一的哈希。仅当其具有相同图像或哈希碰撞为2 ^ 160的机会为1时,才会发生冲突。您可以通过这种方式避免重复图像,因为从文件创建散列会比较慢。

sha1_file

另一个选项是$filename = sha1_file($upload_file) . $ext; ,它将创建一个具有唯一名称的临时文件。

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

基本示例:

tempnam

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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.