1

I am working on a url Shortener and Currently i am facing a problem with Random Generated String. Things i want to do is:

  1. Generate A Random String [ Already Done ]
  2. Searching into Database Whether it exists or not [ Already Done ]
  3. If it already Exists, Generate a new one and Again Proceed for checking [ Stacked !]
  4. 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?

6
  • Can't you just put the link into the database together with the random string. Then have a .php page which you request with p as a get variable that holds the random string, then fetch the url from the database that belongs to that string? Commented Aug 17, 2012 at 22:20
  • I guess you are missing the point. I want to use the string as the get method variable for the linkshortener. Like example.com/XXyZZs. Before i insert it into the DB i have to sure that the same string don't exist. Otherwise it will be conflicted. Commented Aug 17, 2012 at 22:29
  • Instead of checking if the string exists in the database, you can set this column in your database to be unique. Then you can let the while loop only update the string such as: while( !mysql_query($update_query) ) $update_query = "UPDATE tbl SET unique_str='" . randString(10) . "';"; Commented Aug 17, 2012 at 22:42
  • @ribot He should set the column to unique anyway, but he'll still have to deal with generating a new string if the current one is already used. Commented Aug 17, 2012 at 22:44
  • Thats seems not to be a bad idea. Let me try that. thanks :) Commented Aug 17, 2012 at 22:46

1 Answer 1

8

Use a while loop:

$random_string = randString(10);
$is_unique = false;

while (!$is_unique) {
    $result = query_the_database('SELECT id FROM table_with_random_strings WHERE random_string_column = "'.$random_string.'" LIMIT 1');
    if ($result === false)   // if you don't get a result, then you're good
        $is_unique = true;
    else                     // if you DO get a result, keep trying
        $random_string = randString(10);
}

I left the database code generic, since I am not sure what you're using... but I hope it is mysqli or 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 the while loop unnecessary most of the time -- which is a good thing.

echo uniqid(); // 502ec5b8ed2de

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:

http://www.mywebsiteaboutgorillas.com/november-17th-gorillas-gone-wild-topless-apes-live

Such a URL has more meaning to your user than:

http://www.mywebsiteaboutgorillas.com/jh7sj347dfj4

To make a "post slug":

function post_slug($url='', $sep='-') {
    // everything to lower and no spaces begin or end
    $url = strtolower(trim($url));

    // adding - for spaces and union characters
    $find = array(' ', '&', '\r\n', '\n', '+',',');
    $url = str_replace ($find, '-', $url);

    //delete and replace rest of special chars
    $find = array('/[^a-z0-9\-<>]/', '/[\-]+/', '/<[^>]*>/');
    $repl = array('', '-', '');
    $url = preg_replace ($find, $repl, $url);

    if ($sep != '-')
        $url = str_replace('-', $sep, $url);

    //return the friendly url
    return $url; 
}

... 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

Sign up to request clarification or add additional context in comments.

5 Comments

Well that won't be needed currently. I am working on a link shortener. So i need the random string actually. I am using mysql Database. And mysqli . Thanks for your help :)
Glad to help, and welcome to StackOverflow, by the way :) Thanks for posting a good question on your first go!
Thanks for your Welcome note. Well sometime we face a problem that comes with a nice question :)
@OritroAhmed May I humbly suggest that you accept this answer, if indeed it solved your problem? See meta.stackexchange.com/questions/5234/… -- they feed me less if I don't get the points! Then the hitting starts :(
It's good you're a proponent of PDO and mysqli, but it would be even better to put ? in the SQL you're writing rather than demonstrating the improper way to do it first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.