I am working on a url Shortener and Currently i am facing a problem with Random Generated String. Things i want to do is:
- Generate A Random String [ Already Done ]
- Searching into Database Whether it exists or not [ Already Done ]
- If it already Exists, Generate a new one and Again Proceed for checking [ Stacked !]
- if Its Unique, Go for Next Process
Now This Is the code is used for generate Random String
function randString($length, $charset='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {
$str = '';
$count = strlen($charset);
while ($length--) {
$str .= $charset[mt_rand(0, $count-1)];
}
return $str; }
What can i do now?
Use a while loop:
I left the database code generic, since I am not sure what you’re using… but I hope it is
mysqlior PDO 🙂Also wanted to mention, there are functions out there that generate unique strings for you, for example
uniqid. Such functions would probably have more success at generating a unique string in the first go, making thewhileloop unnecessary most of the time — which is a good thing.However, you don’t have as much control over the length, and if that is important than you can stick with your homebrew random generator — just expect the likelihood of collisions to be greater.
Edit Another thing: usually, instead of a random string that is meaningless to your user, many content publishing systems will use the article title. This is called (sometimes) a “post slug”. If you have a title of “November 17th: Gorillas Gone Wild, Topless Apes Live!”, the url would be:
Such a URL has more meaning to your user than:
To make a “post slug”:
… you do still have to watch out for uniqueness there, sometimes CMSes will append the date or id as a pseudo-subdirectory to help mitigate against repetition. You might be able to work something like that into your URL shortener, to give the user at least some indication of what they’re about to click.
Documentation
while– http://us.php.net/manual/en/control-structures.while.phpmysqli– http://us.php.net/manual/en/book.mysqli.phpuniqid– http://php.net/manual/en/function.uniqid.php