Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/247.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 上传时有没有生成随机文件名的方法?_Php_Html - Fatal编程技术网

Php 上传时有没有生成随机文件名的方法?

Php 上传时有没有生成随机文件名的方法?,php,html,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

我创建了一个可以上传任何东西的网站。我的问题是我对这一切都不熟悉。我已经尝试了所有生成随机字符串的代码,但我什么都没有。下面是代码:

<?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";
}

?>

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

使用时间戳(或microtime),这样您就知道每次上传的文件都必然不同

$fileName = "image_".time();
时间戳 返回自Unix纪元(1970年1月1日00:00:00 GMT)以来以秒为单位测量的当前时间

微时间 microtime()返回当前Unix时间戳,单位为微秒。此函数仅在支持gettimeofday()系统调用的操作系统上可用


您可以使用microtime来确保文件名是唯一的

 $file_name = "custom_name_" . microtime(); 
试试这个

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

它将在文件名前面添加日期,因为文件夹限制为65535个文件,所以您需要创建子文件夹。此技术根据时间戳创建3个子文件夹(每个子文件夹有3个字符),然后创建一个随机文件名

//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
为了获得更多的随机性和未来证明(因为如果您同时有多个用户上传,则使用time()和microtime()是很弱的):

以及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;
}
函数的作用是:根据微时间生成一个唯一的ID (以微秒为单位的当前时间)


关于uniqid函数:

仔细研究此代码。这就是你所需要的

<?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();
    }
    ?>

您可以使用md5(microtime())来获得唯一的文件名,即使您一次上载多个文件

我通常使用时间戳来为上载的文件命名唯一的名称。据说move\u uploaded\u file功能失败,每天只允许1个文件。。这不是个好办法。
$fileName = "image_".uniqid();
<?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();
    }
    ?>