Base10 to base64 url shortening

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

提交回复
热议问题