Base10 to base64 url shortening

前端 未结 8 954
小鲜肉
小鲜肉 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:25

    How about this:

    function shorten_int($id){
        $hex = base_convert(id, 10, 16);
        $base64 = base64_encode(pack('H*', $hex));
        //$base64 = str_replace("/", "_", $base64); // remove unsafe url chars
        //$base64 = str_replace("+", "-", $base64);
        //$base64 = rtrim($base64, '='); // Remove the padding "=="
        $replacePairs = array('/' => '_',
                              '+' => '-',
                              '=' => '');
        $base64 = strtr($base64, $replacePairs); // optimisation
        return $base64;
    }
    

提交回复
热议问题