php生成短網址原理與實例

WBOY
發布: 2016-07-25 09:12:47
原創
918 人瀏覽過

例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. }

复制代码


來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板