php generates short url principles and codes

  • 2020-12-16 05:53:56
  • OfStack

php generates short urls

Principle:

1. Do crc32 check on the original website to get the check code.

2. Use sprintf('%u') to convert check codes to unsigned numbers.

3. Perform residual operation on unsigned digits (upper and lower case letters + digits are equal to 62 bits), and the remaining digits are mapped to 62 characters, and the mapped characters are saved. (For example, if the remainder is 10, the mapped characters are A, 0-9 corresponds to 0-9, 10-35 corresponds to ES13en-ES14en, 35-62 corresponds to ES15en-ES16en)

4. Loop until the value is 0.

5. Concatenate all the mapped characters to form code after the short url.

The code is as follows:
 
/**  Generate short url  
* @param String $url  The original site  
* @return String 
*/ 
function dwz($url){ 

$code = sprintf('%u', crc32($url)); 

$surl = ''; 

while($code){ 
$mod = $code % 62; 
if($mod>9 && $mod<=35){ 
$mod = chr($mod + 55); 
}elseif($mod>35){ 
$mod = chr($mod + 61); 
} 
$surl .= $mod; 
$code = floor($code/62); 
} 

return $surl; 

} 

Related articles: