PHP 不重复的随机字符串生成器
我正在尝试编写一个 PHP 函数,它将生成“假定的”随机字符串,无论运行多少次,这些字符串都必须是唯一的。好吧,它可以运行多次才能生成,但最好不要运行很多次。
例如,当您将图像上传到 imgur 时,它会生成一个随机的 5 个字母的 [a-zA-Z] 字符串。如果我想复制这个(在 MySQL 数据库中存储带有唯一键的字符串),而不必重复选择并确保该键不存在,有什么办法吗? 同时,随机性的重要性确实存在,所以我宁愿不选择 1,2,3 (aaaaa,aaaab,aaaac),因为这将完全消除对随机性的需求。
我知道有 52^5 种不同的可能性,但只是出于教育目的(以及未来的算法编写),是否有一种有效的方法来生成这些“独特”“随机”字符串?
[编辑] 我知道唯一+随机(基本上)是不可能的。但是有什么方法可以生成独特的、不明显的字符串吗?谢谢丹麦哥尔!
I'm trying to write a PHP function which will generate "supposedly" random strings which need to be unique regardless of the number of times it is run. Well, it can run more than once in order to generate but preferably not many many times.
For example, when you upload an image to imgur, it generates a random 5-letter [a-zA-Z] string. If I want to duplicate this (store the string with a Unique KEY in a MySQL database), without having to repeating select and ensure that the key does not already exist is there any way?
At the same time, the importance of random does exist, so I'd rather not go 1,2,3 (aaaaa,aaaab,aaaac) as this would completely nullify the need for randomness.
I know there is 52^5 different possibilities but just for educational purposes (and future algorithm writing), is there an efficient method to generate these "unique" "random" strings?
[EDIT] I understand that unique+random is (basically) impossible. But is there any way I can generate unique, non-obvious strings? Thanks danishgoel!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您随机生成任何数据时,您无法保证唯一性。
您只有生成重复项的概率,具体取决于随机算法和随机数据可能性的数量。
这通常非常低,无需担心。
但如果你想保证唯一性,你有两种方法:
请求者的 IP 地址
以及请求时间
,这可以保证生成唯一的数据,因为两个用户不能同时拥有相同的 IP 地址When you are generating any data randomly, you CANNOT GUARANTEE uniqueness.
You only have a probability of generating duplicates, depending on the randomizing algorithm and the number of random data possibilities.
Which is normally extremely low to be of concern.
But if you want to guarantee uniqueness, you have 2 methods:
IP Address of requester
along withrequest time
which is guaranteed to generate unique data as two users cannot have same IP address at SAME time这是依赖时间的,因此不太可能携带副本。
虽然有点长。
This is time reliant, so it is highly unlikely to bring a duplicate.
It is kinda long though.
我发现了一个简单的方法:
...或者...
您还应该阅读 另外两种使用php生成随机字符串的方法,
A simple method I found:
... or...
You should also read two more methods to generate random string using php,