6

在很多情况下,我们需要在创建它们时在服务器上使文件名不同,以防止重复。最常见的答案似乎是,在末尾附加时间戳或将文件名存储在数据库中,并使用这些存储的值来计算新名称。这些都很好,但是,附加一个长的时间戳并不总是非常用户友好,并且存储在数据库中并不总是一种选择。那么,我们如何在通过 php 创建标准文件名时自动增加它?

4

4 回答 4

7

所有这些答案似乎都过分了:

$k = 0;
while(!$result){
    if(!file_exists("file[$k].ext"))
        $result = "file[$k].ext";
    $k++;
}
makefile($result);
于 2015-06-18T14:56:43.223 回答
6

这是我为此目的编写的一个简单函数:

function incrementFileName($file_path,$filename){
 if(count(glob($file_path.$filename))>0)
 {
     $file_ext = end(explode(".", $filename));
     $file_name = str_replace(('.'.$file_ext),"",$filename);
     $newfilename = $file_name.'_'.count(glob($file_path."$file_name*.$file_ext")).'.'.$file_ext;
     return $newfilename;
  }
  else
  {
     return $filename;
  }
}

用法:

$newName = incrementFileName( "uploads/", $_FILES["my_file"]["name"] );
move_uploaded_file($_FILES["my_file"]["tmp_name"],"uploads/".$newName);
于 2013-03-26T09:17:07.857 回答
4

这是一个简短的代码片段,演示了如何开始解决这个问题。

// handle filename collision:
if(file_exists($newFile)) {
    // store extension and file name
    $extension = pathinfo($newFile,PATHINFO_EXTENSION);
    $filename = pathinfo($newFile, PATHINFO_FILENAME);

    // Start at dup 1, and keep iterating until we find open dup number
    $duplicateCounter = 1;
    // build a possible file name and see if it is available
    while(file_exists($iterativeFileName =
                        $newPath ."/". $filename ."_". $duplicateCounter .".". $extension)) {
        $duplicateCounter++;
    }

    $newFile = $iterativeFileName;
}

// If we get here, either we've avoided the if statement altogether, and no new name is necessary..
// Or we have landed on a new file name that is available for our use.
// In either case, it is now safe to create a file with the name $newFile
于 2018-11-07T14:52:15.590 回答
1
function incrementFileName($file_path,$filename){
  $array = explode(".", $filename);
  $file_ext = end($array);
  $root_name = str_replace(('.'.$file_ext),"",$filename);
  $file = $file_path.$filename;
  $i = 1;
  while(file_exists($file)){
    $file = $file_path.$root_name.$i.'.'.$file_ext;
    $i++;
  }
  return $file;
}
于 2013-03-26T10:59:06.633 回答