开发者

does this code guarantee a Unique id

I'm trying to create a unique id that's random. This solution was suggested, but I'm not if it's guaranteed that they'll be unique.

function uid($n) {
    $id_part = base_convert($n, 10, 36);
    $rand_part = str_shuffle('abcdefghijklmnopqrstuvwxyz0123456789');
    return sprintf("%05s%.15s", $id_part, $rand_part);
}

The code uses the unique id from the database auto-incremented id (that's the $n input I'm guessing), then some fill characters are added. It gives supposedly a "unique" 5 chars base-36 primary id + 15 rubbish chars. Can someone confirm if the result will indeed be unique ids or not.

To answer the question, what开发者_如何学编程 am I doing this for exactly. I need to give users a unique id, that doesn't directly equal their user id in the database. This way user 1 does not know that he registered before user 2, but each user still has to have a unique "front id".


It will be unique within the table that $n comes from, as would $n alone without any extra random characters. It will not be globally unique across all applications ever, nor would any fixed length string. All you can guarantee is the probability of generating the same string twice.


You can try inbuilt functionalities like :

http://php.net/manual/en/function.uniqid.php

http://php.net/manual/en/function.com-create-guid.php

Depends how much uniqueness you want to have. If it is only for your application, or globally.

Globally Guid will be a better option.


$token = hash('sha256', rand() . microtime() . $_SERVER['REMOTE_ADDR']) // rand as possible
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜