Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generate random string in php for file name [duplicate]

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.

like image 955
Michael Avatar asked Sep 29 '13 20:09

Michael


People also ask

How to generate random file name in PHP?

= $chars[rand(0,strlen($chars))]; return $name; } //get a random name of the file here $fileName = generateName(); //what we need to do is scan the directory for existence of the current filename $files = scandir(dirname(__FILE__).

How can we create a unique random password in PHP *?

php function password_generate($chars) { $data = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcefghijklmnopqrstuvwxyz'; return substr(str_shuffle($data), 0, $chars); } echo password_generate(7).


1 Answers

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);
like image 133
George Brighton Avatar answered Sep 22 '22 04:09

George Brighton