短地址生成方式有多种 我们这里使用入库的方式
实现方法
生成短地址:原地址入库 返回的主键id 转换64位进制 生成 域名/zqtexds(主键id 64位形式)
解析短地址:访问短地址 路由重写 解析短地址 64位主键转换10进制 根据主键id查询 获取原地址
实现效果如下:
解析后效果:
1.原地址入库
$add['create_time'] = time();
$add['parent_id'] = $task_id;
$add['url'] = 'http://'.$_SERVER['HTTP_HOST'].$value.'task_id/'.$task_id.'.html';
//原地址入库
$url_id = $this->link_model->add($add)
2.生成短地址
$type = $key;
$lk_obj = new \Org\Util\Link(); //实例化短地址类生成短地址
$url = $lk_obj->encodeurl($url_id,$type); //保存短地址
$Task_model->where('id = '.$task_id)->setField($key,$url);
短地址类
class Link {
//解析短地址
public function decodeid($id){
$id = $this->b64dec(base64_decode($id));
return $id;
}
//生成短地址
public function encodeurl($id,$type){
switch ($type) {
case 'get':
$type = 'zqg';
break;
case 'sel_order_url':
$type = 'zqs';
break;
case 'add_order_url':
$type = 'zqa';
break;
}
$url = 'http://'.$_SERVER['HTTP_HOST'].'/'.$type.base64_encode($this->decb64($id));
return $url;
}
private function decb64($dec) { //10进制转换成64进制
if ($dec < 0) {
return FALSE;
}
$map = $this->map('encode');
$b64 = '';
do {
$b64 = $map[($dec % 64)] . $b64;
$dec /= 64;
} while ($dec >= 1);
return $b64;
}
private function b64dec($b64) { //64进制转换成10进制
$map = $this->map();
$dec = 0;
$len = strlen($b64);
for ($i = 0; $i < $len; $i++) {
$b = $map[$b64{$i}];
if ($b === NULL) {
return FALSE;
}
$j = $len - $i - 1;
$dec += ($j == 0 ? $b : (2 << (6 * $j - 1)) * $b);
}
return $dec;
}
private function map($type){
$map = array(
'0'=>0,'1'=>1,'2'=>2,'3'=>3,'4'=>4,'5'=>5,'6'=>6,'7'=>7,'8'=>8,'9'=>9,
'A'=>10,'B'=>11,'C'=>12,'D'=>13,'E'=>14,'F'=>15,'G'=>16,'H'=>17,'I'=>18,'J'=>19,
'K'=>20,'L'=>21,'M'=>22,'N'=>23,'O'=>24,'P'=>25,'Q'=>26,'R'=>27,'S'=>28,'T'=>29,
'U'=>30,'V'=>31,'W'=>32,'X'=>33,'Y'=>34,'Z'=>35,'a'=>36,'b'=>37,'c'=>38,'d'=>39,
'e'=>40,'f'=>41,'g'=>42,'h'=>43,'i'=>44,'j'=>45,'k'=>46,'l'=>47,'m'=>48,'n'=>49,
'o'=>50,'p'=>51,'q'=>52,'r'=>53,'s'=>54,'t'=>55,'u'=>56,'v'=>57,'w'=>58,'x'=>59,
'y'=>60,'z'=>61,'_'=>62,'='=>63
);
//是生成还是解析短地址 转换进制
if($type=='encode'){
$map = array_flip($map);
}
return $map;
}
}
3.解析短地址
解析短地址当然要用到路由重写 tp下的路由重写不再赘述
url重写配置
'/^zqs([\w=]*)$/' => 'Portal/Links/index?code=:1&type=sel',
'/^zqa([\w=]*)$/' => 'Portal/Links/index?code=:1&type=add',
'/^zqg([\w=]*)$/' => 'Portal/Links/index?code=:1&type=get',
$link_model = D('ShortLinks');
$case_model = D('TaskCase');
$b64 = I('get.code');
$type = I('get.type');
$lk_obj = new \Org\Util\Link();//实例化短地址类生成短地址
$id = $lk_obj->decodeid($b64);
if($res = $link_model->field('url,parent_id')->find($id))
{
echo "<script>window.location.href='".$res['url']."'</script>";
exit();
}