generate random string in php for file name

Michael picture Michael · Sep 29, 2013 · Viewed 46.7k times · Source

How would I go about creating a random string of text for use with file names?

I am uploading photos and renaming them upon completion. All photos are going to be stored in one directory so their filenames need to be unique.

Is there a standard way of doing this?

Is there a way to check if the filename already exists before trying to overwrite?

This is for a single user environment (myself) to show my personal photos on my website however I would like to automate it a little. I don't need to worry about two users trying to upload and generating the same filename at the same time but I do want to check if it exists already.

I know how to upload the file, and I know how to generate random strings, but I want to know if there is a standard way of doing it.

Answer

George Brighton picture George Brighton · Sep 29, 2013

The proper way to do this is to use PHP's tempnam() function. It creates a file in the specified directory with a guaranteed unique name, so you don't have to worry about randomness or overwriting an existing file:

$filename = tempnam('/path/to/storage/directory', '');
unlink($filename);
move_uploaded_file($_FILES['file']['tmp_name'], $filename);