Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to code a URL shortener?
    text
    copied!<p>I want to create a URL shortener service where you can write a long URL into an input field and the service shortens the URL to "<code>http://www.example.org/abcdef</code>".</p> <blockquote> <p><strong>Edit:</strong> Due to the ongoing interest in this topic, I've <a href="https://github.com/delight-im/ShortURL" rel="noreferrer">published an efficient solution to GitHub</a>, with implementations for <a href="https://github.com/delight-im/ShortURL/blob/master/JavaScript/ShortURL.js" rel="noreferrer">JavaScript</a>, <a href="https://github.com/delight-im/ShortURL/blob/master/PHP/ShortURL.php" rel="noreferrer">PHP</a>, <a href="https://github.com/delight-im/ShortURL/blob/master/Python/shorturl.py" rel="noreferrer">Python</a> and <a href="https://github.com/delight-im/ShortURL/blob/master/Java/ShortURL.java" rel="noreferrer">Java</a>. Add your solutions if you like :)</p> </blockquote> <p>Instead of "<code>abcdef</code>" there can be any other string with six characters containing <code>a-z, A-Z and 0-9</code>. That makes 56~57 billion possible strings.</p> <p>My approach:</p> <p>I have a database table with three columns:</p> <ol> <li>id, integer, auto-increment</li> <li>long, string, the long URL the user entered</li> <li>short, string, the shortened URL (or just the six characters)</li> </ol> <p>I would then insert the long URL into the table. Then I would select the auto-increment value for "<code>id</code>" and build a hash of it. This hash should then be inserted as "<code>short</code>". But what sort of hash should I build? Hash algorithms like MD5 create too long strings. I don't use these algorithms, I think. A self-built algorithm will work, too.</p> <p>My idea:</p> <p>For "<code>http://www.google.de/</code>" I get the auto-increment id <code>239472</code>. Then I do the following steps:</p> <pre><code>short = ''; if divisible by 2, add "a"+the result to short if divisible by 3, add "b"+the result to short ... until I have divisors for a-z and A-Z. </code></pre> <p>That could be repeated until the number isn't divisible any more. Do you think this is a good approach? Do you have a better idea?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload