I found Marcel Jackwerth's response to How to code a URL shortener? to be a good answer for the problem, however my question is how it'll look in PHP? Here's Marcel's answer:
You need a Bijective Function f
(there must be no x1 != x2
, that will make f(x1) = f(x2)
; and for every y you will find a x so that f(x)=y
). This is necessary so that you can find a inverse function g('abc') = 123
for your f(123)='abc'
function.
I would continue your "convert number to string" approach (however you will realize that your proposed algorithm fails if your id
is a prime and greater than 52).
How to convert the id
to a shortened url:
- Think of an alphabet you want to use. In your case that's [a-zA-Z0-9]. It contains 62 letters.
- Take the auto-generated unique numerical key (auto-incremented
id
): for example 125 (a decimal number) - Now you have to convert the 125 (base 10) to X (base 62). This will then be {2}{1} (2×62+1=125).
- Now map the symbols {2} and {1} to your alphabet. Say {0} = 'a', {25} = 'z' and so on. We will have {2} = 'c' and {1} = 'b'. So '/cb' will be your shortened url.
How to resolve a shortened url abc
to the initial id
:
- If you want to do this in reverse, it's not quite diffcult. 'e9a' will be resolved to "4th,61st,0th letter in alphabet" = {4}{61}{0}, which is 4×62×62 + 61×62 + 0 = 19158. You will then just have to find your database-record with
id
19158.