2
\$\begingroup\$

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;
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Nov 23, 2017 at 19:29
\$\endgroup\$
4
  • \$\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\$ Commented Nov 26, 2017 at 20:28
  • \$\begingroup\$ @KIKOSoftware by secure I️ mean basically never will repeat. I️m not storing sensitive info. \$\endgroup\$ Commented 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\$ Commented Nov 29, 2017 at 0:42
  • \$\begingroup\$ php.net/manual/ru/function.uniqid.php#94959 \$\endgroup\$ Commented Nov 29, 2017 at 10:13

1 Answer 1

1
\$\begingroup\$

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.

answered Nov 28, 2017 at 22:24
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.