Will this code be random enough to generate user ids for a website where people can create posts? Would there be a better method other than running this function and validating it doesn't exist in the database? I would prefer to have a method that I don't need to run a database check but the resulting UID should be 8 characters at most.
/**
* Creates a UID
* @return string 64 Character UID
*/
public static function createUid($length) {
$bytes = random_bytes($length / 2);
$uid = bin2hex($bytes);
return $uid;
}
-
\$\begingroup\$ As far as I understand it, the only demands you have is that the UID should be unique and no more than 8 characters. Please define what you mean by 'secure'? \$\endgroup\$KIKO Software– KIKO Software2017年11月26日 20:28:09 +00:00Commented Nov 26, 2017 at 20:28
-
\$\begingroup\$ @KIKOSoftware by secure I️ mean basically never will repeat. I️m not storing sensitive info. \$\endgroup\$Joe Scotto– Joe Scotto2017年11月28日 22:54:25 +00:00Commented Nov 28, 2017 at 22:54
-
\$\begingroup\$ That is normally not meant by 'secure', it's called 'unique'. They are two very different concepts. \$\endgroup\$KIKO Software– KIKO Software2017年11月29日 00:42:34 +00:00Commented Nov 29, 2017 at 0:42
-
\$\begingroup\$ php.net/manual/ru/function.uniqid.php#94959 \$\endgroup\$Your Common Sense– Your Common Sense2017年11月29日 10:13:27 +00:00Commented Nov 29, 2017 at 10:13
1 Answer 1
Personally, when I need something to be secure and consistently unique is to add a secret to an incrementing ID, which I assume your DB already has.
Your members have ID's and they are incremental, but then you can design a secret phrase or some sort of algorithm to append to that number, and then mcrypt it, or, depending on how secure you need your UID, encrypt in other ways and then concatenate it to your desired length.