PHP无重复的随机字符串生成器 [英] PHP Random String Generator without Repeats

查看:127
本文介绍了PHP无重复的随机字符串生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个PHP函数,该函数将生成应该是"随机字符串,无论运行多少次,该字符串都必须是唯一的.好吧,它可以运行不止一次以便生成,但最好不要运行很多次.

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.

例如,当您将图像上传到imgur时,它会生成一个随机的5个字母的[a-zA-Z]字符串.如果我想重复此操作(将带有唯一键的字符串存储在MySQL数据库中),而不必重复执行select并确保该键尚不存在,那有什么办法呢? 同时,随机性的重要性确实存在,因此我宁愿不要使用1,2,3(aaaaa,aaaab,aaaac),因为这将完全消除对随机性的需求.

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.

我知道有52 ^ 5种不同的可能性,但仅出于教育目的(以及将来的算法编写),是否有一种有效的方法来生成这些唯一的"随机"字符串?

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?

我了解唯一+随机是(基本上)不可能的.但是,有什么方法可以生成唯一的,非显而易见的字符串?谢谢danishgoel!

I understand that unique+random is (basically) impossible. But is there any way I can generate unique, non-obvious strings? Thanks danishgoel!

推荐答案

随机生成任何数据时,都无法保证唯一性.

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:

  1. 搜索先前生成的结果并丢弃重复项(这是您的MySQL方法)
  2. 使用一些您知道的唯一值,然后将该值附加/添加到随机数据中,例如对于Web应用程序,您可以将IP Address of requesterrequest time一起使用,因为两个用户在同一时间不能拥有相同的IP地址,因此可以保证生成唯一数据
  1. Search the previously generated results and discard duplicates (this is your MySQL method)
  2. Use some value which you know is unique, and append/preppend that value to random data, e.g. in case of a web application you can use the IP Address of requester along with request time which is guaranteed to generate unique data as two users cannot have same IP address at SAME time

这篇关于PHP无重复的随机字符串生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆