Principles and examples of generating short URLs in PHP

WBOY
Release: 2016-07-25 09:12:47
Original
914 people have browsed it

Example 1, php generates short URL.

  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. ?>
Copy code

php Principle and code for generating short URL

Perform crc32 verification on the original URL to obtain the verification code, and use sprintf to convert the verification code into an unsigned number.

php generates short URL Principle:

1. Verify the original URL with crc32 and get the verification code.

2. Use sprintf('%u') to convert the check code into an unsigned number.

3. Perform a remainder 62 operation on unsigned numbers (uppercase and lowercase letters + numbers equal 62 bits), map the remainder to 62 characters, and save the mapped characters. (For example, if the remainder is 10, the mapped character is A, 0-9 corresponds to 0-9, 10-35 corresponds to A-Z, and 35-62 corresponds to a-z)

4. Loop until the value is 0.

5. Splice all the mapped characters together to get the code after the short URL.

  1. /**Generate short URL

  2. * @param String $url Original 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. }

Copy code


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template