tags:

views:

409

answers:

6

I've made an image upload script using the move_uploaded_file function. This function seems to overwrite any preexisting file with the new one. So, I need to check if the target location already has a file. If it does then I need to append something to the filename(before the extension so that the file name is still valid) so the filename is unique. I'd like to have the change be minimal instead of something like appending the datetime, if possible.

How can I do this with PHP?

A: 

To check if a file exists, you can use the file_exists function.

To cut the filename, you can use the pathinfo function.

Rémy BOURGOIN
This likely covers my needs. I need to try it out and then I'll accept if it does.
Eugene M
Read all the responses before !Leftnode and Cletus gave you some pretty advices here.
Rémy BOURGOIN
+13  A: 

When uploading files I will nearly always rename them. Typically there will be some kind of database record for that file. I use the ID of that to guarantee uniqueness of the file. Sometimes I'll even store what the client's original filename was in the database too but I'll never keep it or the temporary name because there is no guarantee that information is good, that your OS will support it or that it's unique (which is your issue).

So just rename it to some scheme of your own devising. That's my advice.

If you don't have any database reference, then you could use file_exists() for this but there's no guarantee that between the time of checking if something exists and moving it that something else won't use that same filename that you'll then overwrite. This is a classic race condition.

cletus
A: 

Don't use file_exists() for the reason that it returns true (on *nix systems at least, since directories are specialized files) if the value is a directory. Use is_file() instead.

For example, say something fails and you have a string like:

$path = "/path/to/file/" . $file; // Assuming $file is an empty value, if something failed for example
if ( true === file_exists($path) ) { echo "This returns true"; }
if ( true === is_file($path) ) { echo "You will not read this"; }

It's caused a few problems in the past for me, so I always use is_file() rather than file_exists().

leftnode
+1  A: 

I use date and time functions to generate a random file name based on the time of upload.

barfoon
A: 

I use

$file_name = time() . "_" . $uploaded_file_name;
msarathy
i see what you're doing, and it'll work for 99.999% of the time, but given that time() "only" changes once per second, you could still hit conflicts. using a guid or at least microtime would be a more reliable prefix.
nickf
Yes,$file_name = microtime() . "_" . $uploaded_file_name;thanks nickf
msarathy