php 生成短网址

<?php
 
 原理:

1.将原网址做crc32校验,得到校验码。

2.使用sprintf('%u') 将校验码转为无符号数字。

3.对无符号数字进行求余62操作(大小写字母+数字等于62位),得到余数后映射到62个字符中,将映射后的字符保存。(例如余数是10,则映射的字符是A,0-9对应0-9,10-35对应A-Z,35-62对应a-z)

4.循环操作,直到数值为0。

5.将所有映射后的字符拼接,就是短网址后的code。 //生成短网址方法1 function shortUrl1($url) { if (empty($url)) { return FALSE; } $url = crc32($url); $crc32 = sprintf("%u", $url); $show = ''; while ($crc32 > 0) { $s = $crc32 % 62; if ($s > 35) { $s = chr($s + 61); } elseif ($s > 9 && $s <= 35) { $s = chr($s + 55); } $show .= $s; $x = floor($crc32 / 62); } return $show; } echo shorturl2('http://www.google.com/'); //4whP54 //生成短网址方法2 function shortUrl2($input) { $base32 = array( 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5' ); $hex = md5($input); $hexLen = strlen($hex); $subHexLen = $hexLen / 8; $output = array(); for ($i = 0; $i < $subHexLen; $i++) { // 把加密字符按照8位一组16进制与0x3FFFFFFF(30位1)进行位与运算 $subHex = substr($hex, $i * 8, 8); $int = 0x3FFFFFFF & (1 * ('0x' . $subHex)); $out = ''; for ($j = 0; $j < 6; $j++) { // 把得到的值与0x0000001F进行位与运算,取得字符数组chars索引 $val = 0x0000001F & $int; $out .= $base32[$val]; $int = $int >> 5; } $output[] = $out; } return $output; } $input = 'http://www.google.com/'; $output = shorturl($input); var_dump($output);

  https://blog.csdn.net/weixin_41423450/article/details/84578758

posted @ 2022-10-10 14:30  星云惊蛰  阅读(59)  评论(0)    收藏  举报