我有一个提交的讨论表,上面有图像上传。现在,我想在用户提交其图像时上传一个唯一的文件名,以便我可以显示所有图像的结果,并避免重复的文件名。
我该如何使用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;
Read this documentation on the PHP docs about uniqid for more information。它使用日期时间来输出唯一的标识符字符串。
我认为最简单的方法是将图像名称存储在数据库字段中,然后当用户上载图像时,通过对照现有文件名对其进行验证,以验证文件名称是否唯一。如果您不希望用户必须等到表单提交后出现错误或提示更改其文件名,则可以使用ajax / jquery界面。