What is the best way to generate codes for a URL shortening service in PHP?

I need to use this method to generate codes for the URL shortening service

$code = substr(md5(uniqid(rand(), 1)), 3, 5); 

but in this case, a code of a fixed length is always generated (5).

What if the database has a large number of URLs that cannot withstand five characters here?

sorry for bad english.

+4
source share
1 answer

You will need to save the url just to have a table:

  • URL: id, url

where id is the sequence of automatic increment, and the index column is indexed. Thus, each URL is unique. The easiest way is to simply use an identifier, but you can get it less.

My suggestion was to convert the identifier to and from the base 62 (10 digits, 26 uppercase letters, 26 lowercase letters = 62), or possibly 64 (add _ and -).

By this I mean that 1234 is valid:

1 x 10 3 + 2 x 10 2 + 3 x 10 1 + 4 x 10 0

and there is a fairly simple algorithm for converting a number from and to its base form 10. Thus, the base 62-digit number:

1234 (base 10) = 19 x 62 1 + 56 x 62 0 = Jq

if my math is correct.

The following functions should do what you need.

 $digits = range(0, 9) + range('A', 'Z') + range('a', 'z') function from10($base10) { global $digits; $ret = ''; $nd = count($digits); $n = $nd; while ($base10 > 0) { $r = $base10 % $n; $ret .= $digits[$r]; $n = (int)($base10 / $n); $n *= $nd; } return $ret; } function to10($baseN) { global $digits; $nd = count($digits); $ret = 0; $n = $nd; for ($i=0; $i<strlen($baseN); $i++) { $ret += $n * $baseN[$i]; $n *= $nd; } return $ret; } 

from10() converts 1234 to "qJ" (hopefully) and to10() converts "qJ" to 1234 if my math data is not turned off.

The numbers are actually stored in reverse order (the equivalent of "one hundred twenty three" is written out as "321"), since it is easier to handle and there is no need for the numbers to be in any particular order.

+8
source

Source: https://habr.com/ru/post/1301768/


All Articles