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.
= $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__).
php function password_generate($chars) { $data = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcefghijklmnopqrstuvwxyz'; return substr(str_shuffle($data), 0, $chars); } echo password_generate(7).
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With