Heim  >  Artikel  >  Backend-Entwicklung  >  PHP生成短网址的3种方法代码实例_PHP

PHP生成短网址的3种方法代码实例_PHP

WBOY
WBOYOriginal
2016-06-01 11:52:10882Durchsuche

短网址服务,可能很多朋友都已经不再陌生,现在大部分微博、手机邮件提醒等地方已经有很多应用模式了,并占据了一定的市场。估计很多朋友现在也正在使用。 看过新浪的短连接服务,发现后面主要有6个字符串组成。

太多算法的东西,也没必要去探讨太多,最主要的还是实现,下面是三种方法的代码:

<&#63;php 
 
//纯随机生成方法
function random($length, $pool = '') 
  { 
    $random = ''; 
 
    if (empty($pool)) { 
      $pool  = 'abcdefghkmnpqrstuvwxyz'; 
      $pool  .= '23456789'; 
    } 
 
    srand ((double)microtime()*1000000); 
 
    for($i = 0; $i < $length; $i++) 
    { 
      $random .= substr($pool,(rand()%(strlen ($pool))), 1); 
    } 
 
    return $random; 
  } 
 
 $a=random(6);
print_r($a);  
 
// 枚举生成方法
function shorturl($input) { 
 $base32 = array ( 
  "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",  
"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",  
"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"
  ); 
 
 $hex = md5($input); 
 $hexLen = strlen($hex); 
 $subHexLen = $hexLen / 8; 
 $output = array(); 
 
 for ($i = 0; $i < $subHexLen; $i++) { 
  $subHex = substr ($hex, $i * 8, 8); 
  $int = 0x3FFFFFFF & (1 * ('0x'.$subHex)); 
  $out = ''; 
 
  for ($j = 0; $j < 6; $j++) { 
   $val = 0x0000001F & $int; 
   $out .= $base32[$val]; 
   $int = $int >> 5; 
  } 
 
  $output[] = $out; 
 } 
 
 return $output; 
} 
$a=shorturl("http://www.bitsCN.com");
print_r($a);
//62 位生成方法
 
function base62($x) 
 
{ 
 
$show= ''; 
 
 while($x> 0) { 
 
$s= $x% 62; 
 
if($s> 35) { 
 
$s= chr($s+61);       
 
} elseif($s> 9 && $s<=35) { 
 
$s= chr($s+ 55); 
 
} 
 
$show.= $s; 
 
 $x= floor($x/62); 
 
} 
 
return $show;   
 
} 
 
function urlShort($url) 
 
{ 
 
$url= crc32($url); 
 
$result= sprintf("%u", $url); 
 
return base62($result); 
 
 } 
 
echo urlShort("http://www.bitsCN.com/"); 
 
&#63;>

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn