php生成短网址原理与实例

发布时间:2020-06-19编辑:脚本学堂
本文介绍了php生成短网址的方法,以及php短网址的生成原理,将原网址做crc32校验,得到校验码,使用sprintf将校验码转为无符号数字,有需要的朋友参考下。

例1,php生成短网址。
 

复制代码 代码示例:
<?php 
$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://www.jb200.com".$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);
?>

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。
 

复制代码 代码示例:

<?php
/** 生成短网址
* @param String $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;
}