php如何自定义短网址,php 两种短网址生成方法

使用以下PHP代码可以生成唯一的6位的短网址。

代码如下:

1 <?php2

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 //生成短网址方法2

30 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);

//生成短网址方法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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值