例1,php產生短網址。
- $chars=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",
- "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");
- $salt="www.joneto.com";
- $hash=md5("http://bbs.it-home.org".$salt);
- $rs=array();
- for($i=0;$i<4;$i++){
- $temp=substr($hash, $i*8,8);
- $temp=base_convert($temp, 16, 10) & base_convert("3fffffff", 16, 10);
- $str="";
- for($j=0;$j<6;$j++){
- $subtemp=$temp & intval(base_convert("3d", 16, 10));
- $str.=$chars[$subtemp];
- $temp=$temp>>5;
- }
- unset($temp);
- $rs[]=$str;
- }
- print_r($rs);
- ?>
複製代碼php 產生短網址原理及代碼 將原網址做crc32校正,得到校正碼,使用sprintf將校正碼轉為無符號數字。 php 產生短網址 原理: 1.將原網址做crc32校正,得到校正碼。 2.使用sprintf('%u') 將校正碼轉為無符號數字。 3.對無符號數字進行求餘62操作(大小寫字母+數字等於62位),得到餘數後映射到62個字元中,將映射後的字元儲存。(例如餘數是10,則映射的字元是A,0-9對應0-9,10-35對應A-Z,35-62對應a-z) 4.迴圈操作,直到數值為0。 5.將所有映射後的字元拼接,就是短網址後的code。
/** 產生短網址
- * @param String $url 原網址
- * @return String
- */
- function dwz($url){
$code = sprintf('%u', crc32($url));
$surl = '';
while($code){
- $mod = $code % 62;
- if($mod>9 && $mod<=35){
- $mod = chr($mod + 55);
- }elseif($mod>35){
- $mod = chr($mod + 61);
- }
- $surl .= $mod;
- $code = floor($code/62);
- }
- return $surl;
- }
複製代碼 |