I want to generate a unique filename for uploaded files. They should be 5 characters in length, and have the following characters only: abcdefghijklmnopqrstuvwxyz0123456789
. This is my code:
$chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
$length = 5;
$filename = '';
for($i = 0; $i < $length; $i++)
{
$filename += $chars[mt_rand(0, 36)];
}
echo $filename;
But I always end up with 1 or 2 character long integers, never any string characters. If I run this code:
$chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
$length = 5;
$filename = '';
for($i = 0; $i < $length; $i++)
{
echo $chars[mt_rand(0, 36)];
}
it works fine, and I get the following output: 8iwzf
.
What could I be doing wrong here? Thanks!
5 characters doesn't give you much 'uniqueness' (entropy), so you run the risk of duplicating filenames.
Why not use
$filename = uniqid();
You can add entropy by adding prefixes and other stuff to make chances of duplication (in the real world) nil.
You are adding (+=). You want to concatenate a string using dot.
$filename .= $chars[mt_rand(0, 36)];
Ready-to-use code:
$file_ext = substr($file['name'], -4); // e.g.'.jpg', '.gif', '.png', 'jpeg' (note the missing leading point in 'jpeg')
$new_name = sha1($file['name'] . uniqid('',true)); // this will generate a 40-character-long random name
$new_name .= ((substr($file_ext, 0, 1) != '.') ? ".{$file_ext}" : $file_ext); //the original extension is appended (accounting for the point, see comment above)
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