I have a requirement on a project where
- I need to generate unique ID's.
- ID's must be upper case.
- I cannot check database to see if ID has been used previously.
We expect to have many millions of records added to database every month.
I have tried solutions here: PHP: How to generate a random, unique, alphanumeric string? and while they seem to work at first, my testing has shown there would be duplicates over time.
Now I am looking at using uniqid with a prefix. The problem I found using uniqid without a prefix is that duplicates will be generated when simultaneous requests come into server at the same exact time. I am hoping using a prefix would solve this.
I am thinking of using this function:
private function generate_id()
{
$alpha_numeric = 'ABCDEFGHIJKLMNPQRSTUVWXYZ0123456789';
$max = strlen($alpha_numeric);
$prefix = '';
for ($i = 0; $i < 5; $i++)
{
$prefix .= $alpha_numeric[random_int(0, $max - 1)];
}
return strtoupper(uniqid($prefix));
}
The prefix would be a 5 character alphanumeric string. Would this be enough to satisfy my requirements?
*****Edit*****
Using a UUID as suggested would be the best way to limit the chance of collision but it has been decided to go with the approach above but increase the prefix to 7 characters. The chance of a collision if two ID's where generated at the same millisecond would be around 1 in 8.3 million. That has been deemed acceptable by the higher ups.