当前位置: 首页 > 微博架构, 网站架构 > 正文

一个php的短网址实现算法

关键字:
1 星2 星3 星4 星5 星 (2 次投票, 评分: 5.00, 总分: 5)
Loading ... Loading ...
baidu_share

每个网址用6个字符代替,(32^6) 最多可以拥有1,073,741,824个短网址。
当然,你还可以记录更详细的信息,如访问记录,创建时间等。
如果真不够用了,还可以删掉很久不用的。

function shorturl($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++) {
    $subHex = substr ($hex, $i * 8, 8);
    $int = 0x3FFFFFFF & (1 * ('0x'.$subHex));
    $out = '';
 
    for ($j = 0; $j < 6; $j++) {
      $val = 0x0000001F & $int;
      $out .= $base32[$val];
      $int = $int >> 5;
    }
 
    $output[] = $out;
  }
 
  return $output;
}
$input = 'http://www.chepoo.com/1';
$output = shorturl($input);
 
echo "Input  : $input\n";
echo "Output : {$output[0]}\n";
echo "         {$output[1]}\n";
echo "         {$output[2]}\n";
echo "         {$output[3]}\n";
echo "\n";
 
$input = 'http://www.snippetit.com/2';
$output = shorturl($input);
 
echo "Input  : $input\n";
echo "Output : {$output[0]}\n";
echo "         {$output[1]}\n";
echo "         {$output[2]}\n";
echo "         {$output[3]}\n";
echo "\n";

Output:

 
 
Input : http://www.snippetit.com/1
Output : h0xg4r
bdr3tw
osk2d3
4azfqa
 
Input : http://www.snippetit.com/2
Output : tm5kxb
ceoj2s
yw3dvl
nrmrxl

The function return an array of 4 elements, you can use any one of them. The others can be used as alternative unique code for the input when you found a duplicated code in your database (same code but different input – although it is unlikely to happen but it will happen). Chances to get a duplicated code is about n/(32^6) or n/1,073,741,824 where n is the number of records in your database.

As you can see, the output results are quite random although you only have one character different in the input string. The output is always consistent, for the same input you will always get the same output.

To make the output more unpredictable by the others, you can scramble the values in the $base32 array or/and add in your own private key or/and XOR the value of $val with a value from range 0 to 31.

For example to scramble the values in the $base32 array, you can change the position of the values or/and replace the value with another (make sure the replaced value is URL safe character).

For example to add in private key, you can add in additional string when calling the md5() function, e.g.:

$hex = md5(‘my-secret-key’.$input.’my-another-secret-key’);
For example to XOR the value of $val with value of 18:

$out .= $base32[$val ^ 18];

本文固定链接: http://www.chepoo.com/short-url-php-implementation.html | IT技术精华网

【上一篇】
【下一篇】

一个php的短网址实现算法:等您坐沙发呢!

发表评论