0

in a simple user table while adding users, the primary key "userid" field is automatically unique since it increments automatically. But I want to add another alphanumeric field of maximum length of 8 char which will be unique for each user. The following is the function I used. I got it from a website.

function unique_code($limit)
{
 return substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, $limit);
 }
 echo unique_code(8);

Will it always give me unique value? If yes, then it's okay. But if no, is there any other way?

1
  • Will it always give me unique value? no. why because it includes sha1 and then substr of only 8 chars. Some may collide because first 8 chars are the same. Commented Jul 18, 2020 at 20:55

1 Answer 1

1

as mentioned here , uniqid() can create the same id many times:

<?php
for($i=0;$i<20;$i++) {
    echo uniqid(), PHP_EOL;
}

/** Example of Output:

5819f3ad1c0ce
5819f3ad1c0ce
5819f3ad1c0ce
5819f3ad1c0ce
5819f3ad1c0ce
5819f3ad1c0ce
5819f3ad1c0ce
5819f3ad1c0ce
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6 */

i suggest to use the function that he created instead of using uniqid().

<?php
function uniqidReal($lenght = 13) {
    // uniqid gives 13 chars, but you could adjust it to your needs.
    if (function_exists("random_bytes")) {
        $bytes = random_bytes(ceil($lenght / 2));
    } elseif (function_exists("openssl_random_pseudo_bytes")) {
        $bytes = openssl_random_pseudo_bytes(ceil($lenght / 2));
    } else {
        throw new Exception("no cryptographically secure random function available");
    }
    return substr(bin2hex($bytes), 0, $lenght);
}
Sign up to request clarification or add additional context in comments.

1 Comment

uniqid has a more entropy option: 3v4l.org/iHMO6 also if done in a loop like your example then one would use the unique iteration number to add additional entropy 3v4l.org/sYan5

Your Answer

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.