这段代码保证唯一的id
我正在尝试创建一个随机的唯一 ID。有人提出了这个解决方案,但如果能保证它们是独一无二的,我就不这么认为。
function uid($n) {
$id_part = base_convert($n, 10, 36);
$rand_part = str_shuffle('abcdefghijklmnopqrstuvwxyz0123456789');
return sprintf("%05s%.15s", $id_part, $rand_part);
}
该代码使用数据库自动递增 id 中的唯一 id(我猜测是 $n 输入),然后添加一些填充字符。据说它给出了一个“独特的”5个字符的base-36主id + 15个垃圾字符。有人可以确认结果是否确实是唯一的 id 吗?
回答这个问题,我是什么? 这样做正是为了。我需要给予 用户有一个唯一的ID,但这并不 直接等于他们的用户ID 数据库。这样用户1就不会 知道他先于用户2注册, 但每个用户仍然必须有一个 唯一的“前端 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".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它在
$n
来源的表中是唯一的,就像单独的$n
没有任何额外的随机字符一样。它不会在所有应用程序中都是全局唯一的,任何固定长度的字符串也不会。您所能保证的只是生成相同字符串两次的概率。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.您可以尝试内置功能,例如:
http://php.net/manual/en/function。 uniqid.php
http://php.net/manual/ en/function.com-create-guid.php
取决于您想要拥有多少独特性。如果它仅适用于您的应用程序,或全球范围内。
全球指南将是一个更好的选择。
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.