php 两种短网址生成方法

来源:互联网 发布:数据科学专业 编辑:程序博客网 时间:2024/06/07 18:39
使用以下PHP代码可以生成唯一的6位的短网址。

代码如下:

 1 <?php 2  3  4 //生成短网址方法1 5 function shortUrl1($url) 6 { 7     if (empty($url)) { 8         return FALSE; 9     }10     $url   = crc32($url);11     $crc32 = sprintf("%u", $url);12     $show  = '';13     while ($crc32 > 0) {14         $s = $crc32 % 62;15         if ($s > 35) {16             $s = chr($s + 61);17         } elseif ($s > 9 && $s <= 35) {18             $s = chr($s + 55);19         }20         $show .= $s;21         $x = floor($crc32 / 62);22     }23     return $show;24 }25 26 echo shorturl2('http://www.google.com/');27 //4whP5428 29 //生成短网址方法230 function shortUrl2($input)31 {32     $base32 = array(33         'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',34         'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',35         'q', 'r', 's', 't', 'u', 'v', 'w', 'x',36         'y', 'z', '0', '1', '2', '3', '4', '5'37     );38 39     $hex       = md5($input);40     $hexLen    = strlen($hex);41     $subHexLen = $hexLen / 8;42     $output    = array();43     for ($i = 0; $i < $subHexLen; $i++) {44         // 把加密字符按照8位一组16进制与0x3FFFFFFF(30位1)进行位与运算45         $subHex = substr($hex, $i * 8, 8);46         $int    = 0x3FFFFFFF & (1 * ('0x' . $subHex));47         $out    = '';48         for ($j = 0; $j < 6; $j++) {49             // 把得到的值与0x0000001F进行位与运算,取得字符数组chars索引50             $val = 0x0000001F & $int;51             $out .= $base32[$val];52             $int = $int >> 5;53         }54         $output[] = $out;55     }56     return $output;57 }58 59 $input = 'http://www.google.com/';60 61 $output = shorturl($input);62 var_dump($output);

 

<?php


//生成短网址方法1
function shortUrl1($url)
{
if (empty($url)) {
return FALSE;
}
$url = crc32($url);
$crc32 = sprintf("%u", $url);
$show = '';
while ($crc32 > 0) {
$s = $crc32 % 62;
if ($s > 35) {
$s = chr($s + 61);
} elseif ($s > 9 && $s <= 35) {
$s = chr($s + 55);
}
$show .= $s;
$x = floor($crc32 / 62);
}
return $show;
}

echo shorturl2('http://www.google.com/');
//4whP54

//生成短网址方法2
function shortUrl2($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++) {
// 把加密字符按照8位一组16进制与0x3FFFFFFF(30位1)进行位与运算
$subHex = substr($hex, $i * 8, 8);
$int = 0x3FFFFFFF & (1 * ('0x' . $subHex));
$out = '';
for ($j = 0; $j < 6; $j++) {
// 把得到的值与0x0000001F进行位与运算,取得字符数组chars索引
$val = 0x0000001F & $int;
$out .= $base32[$val];
$int = $int >> 5;
}
$output[] = $out;
}
return $output;
}

$input = 'http://www.google.com/';

$output = shorturl($input);
var_dump($output);

 

原创粉丝点击