php - Duplicate Filename Protection by Incrementation -


first post, , rather asking question proposing answer 1 couldn't find answer for, may else.

the issue saving file uploads locally, , trying find nice way handle duplicate file names.

given filename of filename.ext can form, give first filename of form filename-\d+.ext doesn't exist

   $file = "upload.jpg";     while(is_file($file))     {         preg_match("/\d+\.[^.]*$/", $file, $matches);         if (!$matches)         {             $file = preg_replace('/(\.[^.]*)$/', '-1${1}', $file);             echo $file."<br>";         }         else         {             list($i, $extension) = explode(".",$matches[0]);              $file = preg_replace('/(\d+\.[^.]*)$/', ++$i.".".$extension, $file);         }  }    echo $file; 

hope might someone

this algorithm not scalable. uploading n files same name cause o(n) behavior in algorithm, leading o(n²) total running time, including o(n²) filesystem accesses. that's not pretty server app. can't fixed because of how filesystems work.

better solutions:

  1. store filenames have been used in db table, mapping them use count.
  2. put high-granularity timestamp in filename.
  3. use sha1 (or md5) hash of contents filename. prevents duplicate files being uploaded, if that's important.

use database map filenames human-readable names, if necessary.


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -