tags:

views:

65

answers:

2

I want to create a less than or equal to 10 character unique string for an input string which could be a url

http://stackoverflow.com/questions/ask

OR an alpha numeric string

programming124

but the result should be unique for every input...Is their any function or class that you use for your projects in php... Thanks...

+1  A: 

If you want a unique and random string, you can use the following function to create a random string:

function randString($length) {
    $charset = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    $str = '';
    while ($length-- > 0) {
        $str .= $charset[rand() % 62];
    }
    return $str;
}

After you have generated a new string, look up your database if that string already exists. If so, repeat that step until you’ve generated a unique string. Then store that new string in the database:

do {
    $randString = randString(10);
    // look up your database if $randString already exists and store the result in $exists
} while ($exists);
// store new random string in database
Gumbo
how can I create a simple lookup table? Thanks for the quick response Gumbo
halocursed
Can you please explain...
halocursed
@halocursed: You could use a SQL database.
Gumbo
Gumbo I am actually saving id identifier for users on my website so they can login using email or openid so should I just use an auto increment(for id column) in the database while adding user info...or should I create unique identifier for every user using your method...which one is better?
halocursed
@halocursed: Sorry, I misunderstood your question. I thought you want to create some kind of short URL service. What you need is both a unique and random string. Using a auto-incremeted value doesn’t fulfill the latter criterion of randomness since the values are absolutely predictable.
Gumbo
So what do you recommend?
halocursed
@halocursed: Use an arbitrary random generator and test if that ID already exists. Simply search for *php random string* for the random generator and use a database to store your already generated IDs.
Gumbo
Thanks a lot Gumbo!!!
halocursed
Thanks, again Gumbo..
halocursed
A: 

The simplest function available in php is uniqid. It is a little longer that you had mentioned, and wont work well with load balancing, but if you are doing something super simple, it should work alright.

Kevin Peno