How to increment filename in php to prevent duplicates

前端 未结 4 1618
忘了有多久
忘了有多久 2020-12-10 17:02

In many situations, we need to make the filename different on the server when creating them to prevent duplication. And the most common answer to that seems to be, append th

4条回答
  •  抹茶落季
    2020-12-10 17:29

    Here's a simple function I wrote for this purpose:

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

    USAGE:

    $newName = incrementFileName( "uploads/", $_FILES["my_file"]["name"] );
    move_uploaded_file($_FILES["my_file"]["tmp_name"],"uploads/".$newName);
    

提交回复
热议问题