上传时有何方法生成随机文件名?

时间:2014-03-31 08:07:31

标签: 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";
}

?>

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

8 个答案:

答案 0 :(得分:2)

$fileName = "image_".uniqid();
  

uniqid()函数根据microtime生成唯一ID   (当前时间,以微秒为单位)。

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

答案 1 :(得分:1)

您可以使用缩微时间来确保文件名是唯一的。

 $file_name = "custom_name_" . microtime(); 

答案 2 :(得分:1)

由于文件夹限制为65535个文件,因此您需要创建子文件夹。此技术创建3个子文件夹(每个子文件3个字符),具体取决于时间戳,然后创建随机文件名。

更多随机性和面向未来(因为如果您同时上传多个用户,则使用time()和microtime()会很弱):

//Get the extension of the file
$fileExtension = end(explode(".", $_FILES['item']['name']));
$randOctalName = openssl_random_pseudo_bytes(5);
$randName = bin2hex($randOctalName).".".$fileExtension;

//Save it into uploads/123/456/789/
$path = "";
$timestamp = time();
$path = substr($timestamp,0,3)."/".substr($timestamp,3,3)."/".substr($timestamp,6,3)."/";
$relativePath = './uploads/'.$path;$timestamp = time();
$path = substr($timestamp,0,3)."/".ubstr($timestamp,3,3)."/".substr($timestamp,6,3)."/";
$relativePath = './uploads/'.$path;
_r_mkdir($relativePath);

mkdir递归函数:

private function _r_mkdir($path, $mode = 0755, $recursive = true)
{
    if(empty($path)){
        return false;
    }

    if($recursive) {
        $toDo = substr($path, 0, strrpos($path, '/'));
        if($toDo !== '.' && $toDo !== '..'){
            _r_mkdir($toDo, $mode);
        }
    }

    if(!is_dir($path)){
        mkdir($path, $mode);
    }

    return true;
}

答案 3 :(得分:1)

即使您一次上传多个文件,也可以使用 md5(microtime())获取唯一的文件名

答案 4 :(得分:0)

使用时间戳(或微时间),所以你知道它每次都必须不同

$fileName = "image_".time();

时间戳

  

返回自Unix Epoch(1970年1月1日00:00:00 GMT)以来秒数测量的当前时间。

microtime中

  

microtime()以微秒返回当前的Unix时间戳。此功能仅在支持gettimeofday()系统调用的操作系统上可用。

答案 5 :(得分:0)

//you can use both random and time function to get more unique no count:


 $fileName = 'mypic'.mt_rand(100000, 999999).'_'.time(). $_FILES["file1"]["name"];

use are:-
mt_rand(100000, 999999)// for randm no.
time()// for timestring
$_FILES["file1"]["name"]//also you can give your file name

答案 6 :(得分:-1)

彻底研究此代码。这就是你所需要的一切。

<?php
    if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != "")
    {
      $fileName = $_FILES["avatar"]["name"];
      $fileTmpLoc = $_FILES["avatar"]["tmp_name"];
      $fileType = $_FILES["avatar"]["type"];
      $fileSize = $_FILES["avatar"]["size"];
      $fileError = $_FILES["avatar"]["error"];
      $kaboom = explode(".",$fileName);
      $fileExt = end($kaboom);
      list($width,$height) = getimagesize($fileTmpLoc);
      if($width < 10 || $height < 10)
      {
        header("location: ../message.php?msg=ERROR: That image has no dimensions");
        exit();  
      }
      $db_file_name = rand(100000000000,999999999999).".".$fileExt;
      if($fileSize > 5048576)
      {
        header("location: ../message.php?msg=ERROR: Your image file was larger than 1mb");
        exit();   
      }
      else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) 
      {
        header("location: ../message.php?msg=ERROR: Your image file was not jpg, gif or png type");
        exit();
      }
      else if ($fileErrorMsg == 1) 
      {
        header("location: ../message.php?msg=ERROR: An unknown error occurred");
        exit();
      }
      $sql = "SELECT avatar FROM users WHERE username='$log_username' LIMIT 1";
      $query = mysqli_query($db_conx,$sql);
      $row = mysqli_fetch_row($query);
      $avatar = $row[0];
      if($avatar != "")
      {
        $picurl = "../user/$log_username/$avatar"; 
        if (file_exists($picurl))
        unlink($picurl);
      }
      $moveResult = move_uploaded_file($fileTmpLoc,"../user/$log_username/$db_file_name");
      if ($moveResult != true) 
      {
        header("location: ../message.php?msg=ERROR: File upload failed");
        exit();
      }
      include_once("../php_includes/image_resize.php");
      $target_file = "../user/$log_username/$db_file_name";
      $resized_file = "../user/$log_username/$db_file_name";
      $wmax = 200;
      $hmax = 300;
      img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
      $sql = "UPDATE users SET avatar='$db_file_name' WHERE username='$log_username' LIMIT 1";
      $query = mysqli_query($db_conx, $sql);
      mysqli_close($db_conx);
      header("location: ../user.php?u=$log_username");
      exit();
    }
    ?>

答案 7 :(得分:-3)

试试这个

$now=date('d/m/y');
if(move_uploaded_file($fileTmpLoc, "uploads/$now.$fileName"))

它将添加文件名前面的日期