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:
- store filenames have been used in db table, mapping them use count.
- put high-granularity timestamp in filename.
- 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
Post a Comment