Maison > développement back-end > tutoriel php > php生成短网址原理与实例

php生成短网址原理与实例

WBOY
Libérer: 2016-07-25 09:12:47
original
938 Les gens l'ont consulté

例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 $temp=substr($hash, $i*8,8);
  13. $temp=base_convert($temp, 16, 10) & base_convert("3fffffff", 16, 10);
  14. $str="";
  15. for($j=0;$j $subtemp=$temp & intval(base_convert("3d", 16, 10));
  16. $str.=$chars[$subtemp];
  17. $temp=$temp>>5;
  18. }
  19. unset($temp);
  20. $rs[]=$str;
  21. }
  22. print_r($rs);
  23. ?>
复制代码

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$mod = chr($mod + 55);
  11. }elseif($mod>35){
  12. $mod = chr($mod + 61);
  13. }
  14. $surl .= $mod;
  15. $code = floor($code/62);
  16. }
  17. return $surl;
  18. }
复制代码


Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal