January 10th, 2008
Giving an Uploaded File a Unique Name in PHP
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?




Jan 10th, 2008
3:09 pm
You know you’re a nerd when this kind of thing is actually fun.
I’m not always the best at optimizing code, but I do love the challenge of trying to figure out how to make code do what you want. So, here’s my shot at it.
Replace this line:
$fulldest = str_replace(”.”,”$i.”,$originaldest);
With these two lines:
$ext = strrchr($originaldest, “.”);
$fulldest = str_replace($ext,$i.$ext,$originaldest);
You could do it in one line, but then you’d have to run the strrchr function twice. The first line looks for the last period in the string and returns the period everything after it (which I assume is always the file extension).
The second line uses the first line’s result to search and replace just the file extension and slap the integer variable in front of it. Thus avoiding the “my1.precious1.file1.jpg” problem.
Here is my reference: http://us.php.net/manual/en/function.strrchr.php (I’ve learned so much from php.net)
Thanks for making me think!
Your snippet will likely come in handy.
Jan 22nd, 2008
9:02 pm
@Noah: Good upgrade!
Dec 19th, 2008
11:22 am
Great function!