Home  >  Article  >  Backend Development  >  用PHP实现URL转换短网址的算法

用PHP实现URL转换短网址的算法

WBOY
WBOYOriginal
2016-06-20 12:29:36986browse

短网址(Short URL) ,顾名思义就是在形式上比较短的网址。在Web 2.0的今天,不得不说,这是一个潮流。目前已经有许多类似服务,借助短网址您可以用简短的网址替代原来冗长的网址,让使用者可以更容易的分享链接。

下面是用PHP实现短网址转换的算法,代码如下:

<?php//短网址生成算法class ShortUrl {        //字符表    public static $charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";     public static function encode($url)    {        $key = 'abc'; //加盐        $urlhash = md5($key . $url);        $len = strlen($urlhash);         //将加密后的串分成4段,每段4字节,对每段进行计算,一共可以生成四组短连接        for ($i = 0; $i < 4; $i++) {            $urlhash_piece = substr($urlhash, $i * $len / 4, $len / 4);                        //将分段的位与0x3fffffff做位与,0x3fffffff表示二进制数的30个1,即30位以后的加密串都归零            //此处需要用到hexdec()将16进制字符串转为10进制数值型,否则运算会不正常            $hex = hexdec($urlhash_piece) & 0x3fffffff;             //域名根据需求填写            $short_url = "http://t.cn/";                        //生成6位短网址            for ($j = 0; $j < 6; $j++) {                                //将得到的值与0x0000003d,3d为61,即charset的坐标最大值                $short_url .= self::$charset[$hex & 0x0000003d];                                //循环完以后将hex右移5位                $hex = $hex >> 5;            }             $short_url_list[] = $short_url;        }         return $short_url_list;    }} $url = "http://www.sunbloger.com/";$short = ShortUrl::encode($url);print_r($short);?>

通常我们用四组网址中的第一组即可。

这里需要注意的是,这个算法是不可逆的,因此,通常的做法是将短网址和对应的原网址存入数据库,当访问时,从数据库中取出匹配的原网址,通过301或header进行跳转。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn