Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating unique filename

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!

like image 677
James Dawson Avatar asked Mar 10 '12 18:03

James Dawson


3 Answers

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.

like image 121
fred2 Avatar answered Oct 22 '22 00:10

fred2


You are adding (+=). You want to concatenate a string using dot.

$filename .= $chars[mt_rand(0, 36)];

like image 40
SenorAmor Avatar answered Oct 22 '22 01:10

SenorAmor


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)
like image 26
bromelio Avatar answered Oct 22 '22 00:10

bromelio