How to produce a short unique id in php?
php
Solution
Uniqid is not guaranteed to be unique, even in its full length.
Furthermore, uniqid is intended to be unique only locally. This means that if you create users simultaneously on two or more servers, you may end up with one ID for two different users, even if you use full-length uniqid.
My recommendations:
If you are really looking for globally unique identifiers (i.e. your application is running on multiple servers with separate databases), you should use UUIDs. These are even longer than the ones returned by uniqid, but there is no practical chance of collisions.
If you need only locally unique identifiers, stick with AUTO_INCREMENT in your database. This is (a little) faster and (a little) safer than checking if a short random ID already exists in your database.
EDIT: As it turns out in the comments below, you are looking not only for an ID for the user, but rather you are forced to provide your users with a random login name... Which is weird, but okay. In such case, you may try to use `rand` in a loop, until you get one that does not exist in your database.
Pseudocode:
$min = 1;
do {
$username = "user" . rand($min, $min * 10);
$min = $min * 10;
} while (user_exists($username));
// Create your user here.
Problem
In order to produce a unique Id I suppose I must use the uniqid function in php. But uniqid produces a 13 digits long HEXA number, by default. ``` 4f66835b507db ``` I would like to reduce this number to 7 digits long NUMERIC number but I want to conserve the unicity. Is it possible ? ``` 4974012 ``` This number will be used as User Id. The authentication will be done with thid Id and a password. Some people say uniqid is not unique ! Is it a bad choice ?