Xeoncross
Xeoncross

Reputation: 57244

How do URL shortener calculate the URL key? How do they work?

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?

Upvotes: 12

Views: 3678

Answers (4)

schoetbi
schoetbi

Reputation: 12876

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.

Upvotes: 1

Topera
Topera

Reputation: 12389

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

Upvotes: 2

Parker
Parker

Reputation: 8851

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.

Upvotes: 0

Xeoncross
Xeoncross

Reputation: 57244

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.

Upvotes: 2

Related Questions