Skip to content

Instantly share code, notes, and snippets.

@nathggns
Created September 21, 2013 18:34
Show Gist options
  • Save nathggns/6652997 to your computer and use it in GitHub Desktop.
Save nathggns/6652997 to your computer and use it in GitHub Desktop.
base64url functionality for php
<?php
function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
function base64url_decode($data) {
return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
}
@nomis
Copy link

nomis commented Sep 21, 2013

Adding the '=' back is not necessary (and your str_pad() doesn't do so correctly).

@bshaffer
Copy link

bshaffer commented Mar 3, 2015

yes, if you want to add back the pad (which is optional), this should be:

function base64url_decode($data) { 
    return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) + (strlen($data) % 4), '=', STR_PAD_RIGHT)); 
}

@kumirska
Copy link

Thks!

@xsddz
Copy link

xsddz commented May 4, 2016

i think should be:

function base64url_decode($data) { 
    return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) + 4 - (strlen($data) % 4), '=', STR_PAD_RIGHT)); 
}

@mnpenner
Copy link

mnpenner commented Aug 17, 2016

What lp0 said is correct -- you don't need to pad the string before decoding it. Thus, the decode function should really be:

function base64url_decode($data) {
    return base64_decode(strtr($data, '-_', '+/'));
}

I've unit tested this.

@maaaddog
Copy link

Since base64_decode() does not bother about "=" signs at the end, you can omit str_pad(..) as remarked by lp0 and mnpenner above.

However, if one will do the padding "manually" (for what reason ever), the pad_length in str_pad() should look like: strlen($data) + (4 - strlen($data) % 4) % 4. @xsddz: Your code is close, but the case when strlen($data) % 4 = 0 should not insert any "=" at the end (your code appends 4x "=" in this case).

@yesitisme
Copy link

@yesitisme
Copy link

why fiddle with base64 why dont you just pass it on rawurlencode/rawurldecode?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment