PHP Random String Generator without Repeats

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!


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