Base10 to base64 url shortening

前端 未结 8 959
小鲜肉
小鲜肉 2021-01-03 05:08

I\'m coding an url shortener function for a project in which I\'m learning php, here is the code (btw I suppose that global here is not a good thing to do :P):<

8条回答
  •  暖寄归人
    2021-01-03 05:22

    These two functions are very convenient, thanks to @malhal:

    function shorten_int($id)
    {
        $id=dechex($id);
        $id=strlen($id)%2===0?hex2bin($id):hex2bin('0'.$id);
        $id=base64_encode($id);
        $id=strtr($id, array('/'=>'_', '+'=>'-', '='=>''));
        return $id;
    }
    
    function unshorten_int($id)
    {
        $id=strtr($id, array('-'=>'+', '_'=>'/'));
        $id=base64_decode($id);
        $id=bin2hex($id);
        return base_convert($id, 16, 10);
    }
    
    echo shorten_int(43121111)."\n";
    echo unshorten_int(shorten_int(43121111))."\n";
    

提交回复
热议问题