Short Url(短网址)实现方式

标签 : ,

现在提供Short Url(短网址)的网站越来越多了,特别是Twitter的助Short Url的一臂之力,越来越多的人开始使用Short Url-短网址,现在比较流行的几个Short Url网站有

TinyURL
http://tinyurl.com/

Bit.Ly
http://bit.ly/

Is.Gd
http://is.gd/

等等,Short Url的作用在于把长的Url缩成短的Url,比如,我前两天些的一篇博客,Url是http://i.laoer.com/think-about-http-get-chinese-encode-error.html,我们采用TinyURL,转成的Url是http://tinyurl.com/d4zw8x,只有25个字符,短了很多,请求http://tinyurl.com/d4zw8x的时候,tinyurl会把请求通过HTTP 301转到http://i.laoer.com/think-about-http-get-chinese-encode-error.html上。

实现Short Url的功能并不复杂,但最关键的就是这个短代码要够短,而且需要唯一,我们的例子是“d4zw8x”,6位,还有就是用户输入的同一个Url,应该返回唯一的Short Url,用户在请求长的Url之后,先从数据库查找一下这个长Url是否存在,如果存在,就直接取出其对应的短代码,如果不存在,则生成短代码,与用户的长Url同时保存在数据库中。

最核心的这个短代码的实现方式,我在网上找了两个

第一个是纯随机数的算法,来自Short URL Script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function random($length, $pool = '')
    {
        $random = '';
 
        if (empty($pool)) {
            $pool    = 'abcdefghkmnpqrstuvwxyz';
            $pool   .= '23456789';
        }
 
        srand ((double)microtime()*1000000);
 
        for($i = 0; $i < $length; $i++) 
        {
            $random .= substr($pool,(rand()%(strlen ($pool))), 1);
        }
 
        return $random;
    }

另一个算法来自http://www.snippetit.com/2009/04/php-short-url-algorithm-implementation/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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;
}

其返回的是一个4个元素的数组,应为存在可能的重复性,你可以依次使用这4个元素。

Short Url的算法应该还有一些,Short Url网站的作用除了缩短网址以外,在使用者不断增加之后,可以积累庞大的网址信息,这对统计分析是很有用的。

Comments:

发表评论

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word