Example 1, php generates short URL.
-
- $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);
- ?>
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.
-
-
/**Generate short URL - * @param String $url Original 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;
- }
-
Copy code
|