PHP Random String Generator without Repeats
I'm trying to write a PHP function which will generate "supposedly" random strings which need to be un开发者_如何学JAVAique 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!
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:
- Search the previously generated results and discard duplicates (this is your MySQL method)
- 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 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.
$randString = date("Ymdhis") . rand(10000, 99999);
It is kinda long though.
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,
精彩评论