Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment filename in php to prevent duplicates

Tags:

php

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 the timestamp at the end or store the filename in the db and use those stored values to compute new name. These are good and all, but, appending a long time-stamp isn't always very user-friendly, and storing in the db isn't always an option. So, how can we auto-increment a standard filename while creating it via php?

like image 531
Bluemagica Avatar asked Mar 26 '13 09:03

Bluemagica


3 Answers

All these answers seem overkill:

$k = 0;
while(!$result){
    if(!file_exists("file[$k].ext"))
        $result = "file[$k].ext";
    $k++;
}
makefile($result);
like image 123
Robert Pounder Avatar answered Sep 30 '22 12:09

Robert Pounder


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);
like image 44
Bluemagica Avatar answered Sep 30 '22 11:09

Bluemagica


Here is a short code snippet that demonstrates how you might start solving this problem.

// 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
like image 40
Jade Steffen Avatar answered Sep 30 '22 12:09

Jade Steffen