Home  >  Article  >  Backend Development  >  PHP implements URL long connection generation short link operation

PHP implements URL long connection generation short link operation

巴扎黑
巴扎黑Original
2016-11-23 11:44:312381browse

Short link, in layman’s terms, is to convert a long URL into a short URL string through program calculation and other methods.

The advantages of this are: 1. Content needs; 2. User-friendly; 3. Easy to manage.

​ Early short links were widely used on image upload websites to reduce the number of code strings by shortening the number of URL link words. It is easier for users to quote the URL and write it into the code to "save" character space. It is commonly used in online store image classification. Due to character restrictions, short links are used to achieve the purpose of external link images. Since the popularity of Weibo, due to the limited character count of Weibo, short links have also become popular on Weibo websites to save word count and give bloggers space to publish more text.

<?php
/**
 * 由长连接生成短链接操作
 * 
 * 算法描述:使用6个字符来表示短链接,我们使用ASCII字符中的&#39;a&#39;-&#39;z&#39;,&#39;0&#39;-&#39;9&#39;,&#39;A&#39;-&#39;Z&#39;,共计62个字符做为集合。
 *      每个字符有62种状态,六个字符就可以表示62^6(56800235584),那么如何得到这六个字符,
 *           具体描述如下:
 *  1. 对传入的长URL+设置key值 进行Md5,得到一个32位的字符串(32 字符十六进制数),即16的32次方;
 *        2. 将这32位分成四份,每一份8个字符,将其视作16进制串与0x3fffffff(30位1)与操作, 即超过30位的忽略处理;
 *  3. 这30位分成6段, 每5个一组,算出其整数值,然后映射到我们准备的62个字符中, 依次进行获得一个6位的短链接地址。
 *
 * @author flyer0126
 * @since 2012/07/13
 */
function shortUrl( $long_url )
{
    $key = &#39;flyer0126&#39;;
    $base32 = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
    // 利用md5算法方式生成hash值
    $hex = hash(&#39;md5&#39;, $long_url.$key);
    $hexLen = strlen($hex);
    $subHexLen = $hexLen / 8;
    
    $output = array();
    for( $i = 0; $i < $subHexLen; $i++ )
    {
    // 将这32位分成四份,每一份8个字符,将其视作16进制串与0x3fffffff(30位1)与操作
    $subHex = substr($hex, $i*8, 8);
    $idx = 0x3FFFFFFF & (1 * (&#39;0x&#39; . $subHex));
   
    // 这30位分成6段, 每5个一组,算出其整数值,然后映射到我们准备的62个字符
    $out = &#39;&#39;;
    for( $j = 0; $j < 6; $j++ )
    {
    $val = 0x0000003D & $idx;
    $out .= $base32[$val];
    $idx = $idx >> 5;
    }
    $output[$i] = $out;
    }
    
    return $output;
}
  
$url = &#39;http://flyer0126.iteye.com/&#39;;
$ret = shortUrl($url);
var_dump($ret);
################ 打印结果 ################
/* array(4) {
[0]=>
string(6) "2aEzqe"
[1]=>
string(6) "Rj6Bve"
[2]=>
string(6) "f2mQvi"
[3]=>
string(6) "z2eqYv"
} */

#Save the url and short link results into the database, and choose one of them for display.


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