tags:

views:

184

answers:

5

How do URL shortener's like bit.ly calculate a random key for each link? What algorithm would I need to know to create my own?

+1  A: 

Maybe they store it in the database and just give you an link id. When you query this key they look in their database and forward you to the stored real link. To encode the id something like base64 (or similar) might be used.

schoetbi
It's base64 buddy :)
Topera
well obviously he knew that since that's what he linked to
advs89
linking to the English version would've been nice though
advs89
fixed that:-) I really need to get the english wikipedia plugin for firefox...
schoetbi
+1  A: 

I think they DON'T random a new key and checks if exists in database, because it its slower than just use a sequencial number and apply some criptography algoritm to convert sequencial id to a UNIQUE string.

Ex:

idUrl = 1003;
urlCode = doSomething(idUrl); // 161Llz

URL to use: http://bit.ly/161Llz

Tks: mykhal and nick johnson

Topera
.. and then they hope there would be no collision :)
mykhal
Cryptography has nothing to do with this.
Nick Johnson
A: 

Yes, database, no algorithm.

Lothar
A: 

So far I found the code from http://briancray.com/2009/08/26/free-php-url-shortener-script/

function getShortenedURLFromID ($integer, $base = ALLOWED_CHARS)
{
    $length = strlen($base);
    while($integer > $length - 1)
    {
        $out = $base[fmod($integer, $length)] . $out;
        $integer = floor( $integer / $length );
    }
    return $base[$integer] . $out;
}

and the more complex answer by Marcel J. mentioned above.

Xeoncross
+1  A: 

They most likely store it in a database and just generate the key randomly. I assume this because you can make your own key, and if they just decoded it you wouldn't be able to choose it yourself.

As for how to do it, you could just create a database in mySQL and have it hold the key and full site. Just search it for the key and then redirect the user to the full site.

Parker
Thanks, but I know how to store the key - my question is how do they "calculate a random key for each link?"
Xeoncross
There's lots of ways. They may just do something as simple as come up with a few random numbers, and then assign a letter for each number and stick them all together. The fact that they use a database to store and look them up means they can use any method they wish, and that their algorithm doesn't have to take into account the actual URL
Parker