Reputation: 2495
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...
Upvotes: 0
Views: 611
Reputation: 655359
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
Upvotes: 2
Reputation: 9196
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.
Upvotes: 0