PHP Random String Generator without Repeats

偶尔善良 提交于 2019-12-11 10:43:23

问题


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!


回答1:


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. 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



回答2:


A simple method I found:

$charset = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$rand_str = '';
$desired_length = 10;
while(strlen($rand_str) < $desired_length)
  $rand_str .= substr(str_shuffle($charset), 0, 1);

... or...

$desired_length = 10;
echo base64_encode(openssl_random_pseudo_bytes($desired_length));

You should also read two more methods to generate random string using php,



来源:https://stackoverflow.com/questions/7480489/php-random-string-generator-without-repeats

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!