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 algori开发者_如何学运维thm would I need to know to create my own?
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.
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
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.
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.
精彩评论