短链接
2022-01-11 08:29 / 浏览量:1367

1.短连接处理方法

传入长链接地址转换为62位进制字符串,后续入库保存,参数识别

// 短链接id转换
function short_url_code($data){  
    static $map = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";  
    $hash = bcadd(sprintf('%u',crc32($data)) , 0x100000000);  
    $str = "";  
    do  {      
        $str = $map[bcmod($hash, 62) ] . $str;      
        $hash = bcdiv($hash, 62);  
    }  while ($hash >= 1);  
    return $str;
}

2.创建数据表

short_url_code 保存转化后的短连接识别码

Schema::create('long_short_url', function (Blueprint $table) {       
     $table->increments('id');        
     $table->string('name')->nullable()->comment('名称');        
     $table->string('long_url')->nullable()->comment('长链接');        
     $table->string('short_url_code')->nullable()->comment('短链接码');        
     $table->unsignedInteger('hits')->default(0)->comment('访问次数');        
     $table->unsignedTinyInteger('status')->default(0)->comment('状态');        
     $table->timestamps();
});


3.路由

设置路由规则,code为短链接码

可以放置在短网址的二级域名下,如t.xxx.com/s/code

$router->get('s/{code}', 'ShortUrlController@shortToLongUrl');

4.控制器

调用LongShortUrl::getCacheStatic()获取短链接码code为键长链接地址为值的缓存数组,不存在去数据查询,正式上线只保留缓存部分。

如需做跳转统计的话,需做缓存计数,定时获取更新。

class ShortUrlController extends Controller{
    public function shortToLongUrl($code){
        $url = '';
        //cache
        $caches = LongShortUrl::getCacheStatic();
        if(isset($caches[$code])) $url = $caches[$code];
        //mysql
        if(!$url){
            $item = LongShortUrl::where([
                ['short_url_code',$code],
                ['status',1]
                ])->first();
            if($item) {     
                $url = $item->long_url;
                $item->hits++;
                $item->save();
            }
        }
        if(!$url) abort(404); 
        return redirect($url);
    }
}