It’s been a while since I’ve done a technical post with code snippets, so I thought I’d share a function that I use at least every week. The majority of my work is with custom CMS or the occasional intranet. In both cases I’m regularly dealing with code where the visitor can upload files to the web site. Maybe it’s pictures or PDFs or something else entirely. In any case, I have a simple function that I use to make sure the filename is unique.
function uniqueName($folderpath,$filename) {
$adjname = str_replace(” “,”_”,$filename);
$fulldest = $folderpath.$adjname;
$originaldest = $fulldest;
for ($i=1; file_exists($fulldest); $i++) {
$fulldest = str_replace(”.”,”$i.”,$originaldest);
}
return $fulldest;
}
If you tried to upload a file called filename.jpg to a directory where that name already exists, this function would return filename1.jpg.
Flaws: The immediate flaw that jumps out at me when I look at this function is that if someone had a filename with multiple periods, such as my.precious.file.jpg, the function would return my1.precious1.file1.jpg. Since the file names are usually just stored in a database for me, this hasn’t come up as a problem, but it’s something to be aware of.
Any readers our there want to offer their improved versions of this function?