wordpress_queries
wordpress_queries

Reputation: 83

Create unique plus random alphanumeric string

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?

Upvotes: 0

Views: 1186

Answers (1)

GNassro
GNassro

Reputation: 1071

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);
}

Upvotes: 1

Related Questions