Appropriately rename uploaded file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Rem
Forum Newbie
Posts: 3
Joined: Mon Jul 12, 2010 8:49 am

Appropriately rename uploaded file

Post by Rem »

Hi there

I have a script that allows me to upload a file to my server. All this works great and all, but I was thinking on how to avoid collision with file names. For example two people upload an image with the same file name and extension which causes the newly uploaded one to overwrite the old one. I don't want that!

For my question, is there a function or something that will generate a unique string for a file?

I was also thinking of doing something like this to generate a unique file name:

Code: Select all

$file_name = "myimage.png";
$file_extension = "." . substr(strrchr($file_name,'.'),1);

$newFile = substr(time(),-7) . hash('adler32',$file_name) . $file_extension;
Is the above feasible? Should I suspect a collision any time soon?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Appropriately rename uploaded file

Post by requinix »

uniqid with the time as the prefix is generally more than adequate.
Post Reply