php - 有什么方法可以在上传时生成随机文件名吗?

标签 php html

我创建了一个可以上传任何内容的网站。我遇到的问题是我对这一切都是新手。我已经尝试了所有生成随机字符串的代码,但我什么也没有。无论如何,这是代码:

<?php

$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
    echo "ERROR: Please browse for a file before clicking the upload button.";
    exit();
}
if(move_uploaded_file($fileTmpLoc, "uploads/$fileName")) {
    echo '<a href="uploads/'.$fileName.'"><input type="button" class="button"    
    value="Download" /></a>';
} else {
    echo "move_uploaded_file function failed";
}

?>

是否有一种方法可以生成随机文件名,以便当有人上传与服务器上已有文件同名的文件时,它不会覆盖现有文件?

最佳答案

$fileName = "image_".uniqid();

The uniqid() function generates a unique ID based on the microtime (current time in microseconds).

关于uniqid功能: http://www.php.net/manual/en/function.uniqid.php

关于php - 有什么方法可以在上传时生成随机文件名吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22756507/

相关文章:

html - svg 过滤器不适用于 FF with godaddy

html - 浏览器底部的div

html - 中心 TextBoxFor 与列中的图标

javascript - 处理 Javascript 事件的正确方法

php - 有人能帮我弄清楚为什么这个邮政编码类找不到范围内的邮政编码吗?

php - 以正确的方式使用 while 和 foreach 显示 mysql

php - WordPress php : Way to test if pages are children of a parent page?

html - 当我使用 h-100 类时,容器外的内容(在移动设备上)被破坏

php - Gitignore Laravel 供应商文件夹

javascript - 动态下拉列表 - 想要一种将输入存储在变量中的方法