Skip to content

Instantly share code, notes, and snippets.

@muffycompo
Created July 10, 2014 23:05
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save muffycompo/a378dcfa73c3cf354eb8 to your computer and use it in GitHub Desktop.
Save muffycompo/a378dcfa73c3cf354eb8 to your computer and use it in GitHub Desktop.
PHP Helper functions for Safe Base64 URL encode
<?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));
}
?>
@maaaddog
Copy link

The pad_length in str_pad(...) in your base64url_decode() function is wrong. See php.net (http://php.net/manual/en/function.str-pad.php ): "If the value of pad_length is negative, less than, or equal to the length of the input string, no padding takes place". Since base64_decode() does not bother about "=" signs at the end, you luckily get the right code though. But you can get this more efficiently by:
function base64url_decode($b64url) { return base64_decode(strtr($b64url, '-_', '+/')); }

Addendum: If you want to do the padding "manually" right, you should exchange strlen($data) % 4 with strlen($data) + (4 - strlen($data) % 4) % 4 in your base64url_decode($data) function.

@danielemontesi
Copy link

Wrong example, the @maaaddog's comment is right

@raat1979
Copy link

shortest possible I could come up with to pad correctly was

str_repeat("=",-strlen($data) & 3)

wrapping it:
return base64_decode(strtr($b64url, '-_', '+/').str_repeat("=",-strlen($str) & 3));

@malau1
Copy link

malau1 commented Jan 16, 2020

@raat1979 thank you !

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