Base10 to base64 url shortening

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

    Just a couple of little tweaks needed, the main two were to make the the alphabet zero indexed rather than one-indexed, and to subtract the remainder from the id before dividing

    function shorten($id)
    {
        $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-';
        $shortenedId = '';
        while($id>0) {
            $remainder = $id % 64;
            $id = ($id-$remainder) / 64;     
            $shortenedId = $alphabet{$remainder} . $shortenedId;
        };
        return $shortenedId;
    }
    

    and here's a further modified version which... well I just like

    function shorten($id, $alphabet='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-')
    {
        $base = strlen($alphabet);
        $short = '';
        while($id) {
            $id = ($id-($r=$id%$base))/$base;     
            $short = $alphabet{$r} . $short;
        };
        return $short;
    }
    

    EDIT: sorted concatenation to be the same as the OPs

    0 讨论(0)
  • 2021-01-03 05:38

    You can use the pack.

    $int = 1129717211140920362;
    
    $byte = pack('J*', $int);    
    echo base64_encode($byte); //= D62P0WqzFCo=
    

    It will result in D62P0WqzFCo=, it is correct, because the $int is an int64 and uses 64 bits. The Base64 uses 6 bits for each character, so they need ~11 characters.

    To decode use:

    $base64 = 'D62P0WqzFCo=';
    
    $byte = base64_decode($base64);
    echo unpack('J*',  $byte)[1]; //= 1129717211140920362
    

    It will return 1129717211140920362. ;)


    It was based in the answer on the Stackoverflow in Portuguese.

    0 讨论(0)
提交回复
热议问题