Home  >  Article  >  php教程  >  PHP generates short URL | two implementation methods

PHP generates short URL | two implementation methods

大家讲道理
大家讲道理Original
2016-11-08 17:31:551958browse

<?php
/**
 * Created by PhpStorm.
 * User: yangyulong/anziguoer@sina.com
 * Date: 2015/5/28
 * Time: 15:55
 */
function shortUrl($url){
    $base32 = array (
        &#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, &#39;h&#39;,
        &#39;i&#39;, &#39;j&#39;, &#39;k&#39;, &#39;l&#39;, &#39;m&#39;, &#39;n&#39;, &#39;o&#39;, &#39;p&#39;,
        &#39;q&#39;, &#39;r&#39;, &#39;s&#39;, &#39;t&#39;, &#39;u&#39;, &#39;v&#39;, &#39;w&#39;, &#39;x&#39;,
        &#39;y&#39;, &#39;z&#39;, &#39;0&#39;, &#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;4&#39;, &#39;5&#39;
    );
 
    $hex = md5($url);
    $hexLength = strlen($hex);
    $subHexLen = $hexLength / 8;
 
    $output = array();
    for ($i = 0; $i < $subHexLen; $i++) {
        //每循环一次取到8位
        $subHex = substr ($hex, $i * 8, 8);
        $int = 0x3FFFFFFF & (1 * (&#39;0x&#39;.$subHex));
        $out = &#39;&#39;;
 
        for ($j = 0; $j < 6; $j++) {
            $val = 0x0000001F & $int;
            $out .= $base32[$val];
            $int = $int >> 5;
        }
 
        $output[] = $out;
    }
 
    return $output;
}
 
 
function shortUrl2($url){
    $result = sprintf("%u",crc32($url));
    $show = &#39;&#39;;
    while($result  >0){
        $s = $result % 62;
        if($s > 35){
            $s=chr($s+61);
        }elseif($s>9 && $s<=35){
            $s=chr($s+55);
        }
        $show .= $s;
        $result = floor($result / 62);
    }
 
    return $show;
}
 
echo shortUrl2(&#39;http://baidu.com&#39;);

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