php產生短網址原理與執行個體

來源:互聯網
上載者:User

例1,php產生短網址。

  1. $chars=array("a","b","c","d","e","f","g","h",
  2. "i","j","k","l","m","n","o","p",
  3. "q","r","s","t","u","v","w","x",
  4. "y","z","0","1","2","3","4","5",
  5. "6","7","8","9","A","B","C","D",
  6. "E","F","G","H","I","J","K","L",
  7. "M","N","O","P","Q","R","S","T",
  8. "U","V","W","X","Y","Z");
  9. $salt="www.joneto.com";
  10. $hash=md5("http://bbs.it-home.org".$salt);
  11. $rs=array();
  12. for($i=0;$i<4;$i++){
  13. $temp=substr($hash, $i*8,8);
  14. $temp=base_convert($temp, 16, 10) & base_convert("3fffffff", 16, 10);
  15. $str="";
  16. for($j=0;$j<6;$j++){
  17. $subtemp=$temp & intval(base_convert("3d", 16, 10));
  18. $str.=$chars[$subtemp];
  19. $temp=$temp>>5;
  20. }
  21. unset($temp);
  22. $rs[]=$str;
  23. }
  24. print_r($rs);
  25. ?>
複製代碼

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。

  1. /** 產生短網址

  2. * @param String $url 原網址
  3. * @return String
  4. */
  5. function dwz($url){

  6. $code = sprintf('%u', crc32($url));

  7. $surl = '';

  8. while($code){

  9. $mod = $code % 62;
  10. if($mod>9 && $mod<=35){
  11. $mod = chr($mod + 55);
  12. }elseif($mod>35){
  13. $mod = chr($mod + 61);
  14. }
  15. $surl .= $mod;
  16. $code = floor($code/62);
  17. }
  18. return $surl;
  19. }

複製代碼
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.