Land
Land

Reputation: 119

Returning only 4 characters from uniqid

Currently I am using the following code to generate a random name for my uploaded file.

$file_upload_name = uniqid('', true) . '.' . $file_type; 

This returns something that looks like this 59c7b4868f4776.27613088.mp3 how can I turn this into something that looks like this 5vh2.mp3 so that it looks cleaner when presented to a user?

Upvotes: 1

Views: 3343

Answers (2)

Andreas
Andreas

Reputation: 23968

This should give you a unique four char name.
It will generate a random name and see if it already exists, if it does generate a new.
Else echo it.

$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$shuffled = substr(str_shuffle($chars),0,4);
While(file_exists($shuffled.".mp3"){
    $shuffled = substr(str_shuffle($chars),0,4);
}

Echo $shuffled.".mp3";

Upvotes: 2

MinistryOfChaps
MinistryOfChaps

Reputation: 1484

EDIT: a good point from salathe in the comments:

The first 8 characters of the uniqid() return value (minus any provided prefix) represent the Unix timestamp at the time of the function call. Using only the first 4 characters means that the value will only change every 2^16 seconds (~18 hours). For example, if this code were executed at any time between (and including) 2017-09-24T00:44:48Z and 2017-09-24T18:57:03Z it would return the same "unique" value.

You may will have collision issues with only four characters considering the first 4 values will only change around every 18 hours (assuming you are calling this script at least 2 two times within 18 hours).

Using the last four characters would be more 'unique'. If you need to use the uniq function you can use the substr function.

$unique = uniqid('', true);
$file_name = substr($unique, strlen($unique) - 4, strlen($unique));
$file_upload_name = $file_name . "." . $file_type;

Be aware having videos with only four characters lessens the uniqueness of video IDs and increases the collision rate of a generated file name being the same.

Upvotes: 2

Related Questions