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?
Basically, when the URL shortener gives you your shortened URL, it "remembers" the full address. When other users go to the shortened URL, they will be automatically redirected to the full address. The webpage will still exist at the longer URL—the shortened URL is simply a shortcut to make the link easier to manage.
To create a URL shortener, we'll need a text input area and a button, then add the script tag. Create the index. php file inside the shorten-url directory and open it using VS code. In folder shorten-url , we will also add script.
Visitor clicks a shortened link (shortened URL) Ad is displayed on an intermediate page – you earn money. The visitor is redirected from the intermediate page to the destination page (long URL)
In the list of APIs, make sure the status is ON for the Google URL Shortener API. - In the sidebar on the left, select Credentials. - [b]Public API access[/b]:- To create an API key, click Create new Key and select "Server key".
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With