Skip to navigation

malevolent design weblog

This blog is now defunct, but you can find more stuff over at my personal site

Encode/Decode URL Data As Base64 In PHP

When putting strings into URLs, it can be useful to apply something other than plain percent-encoding or hexadecimal. Things like hashes are rather long as hex, and binary data or strings of multi-byte characters can go on forever when percent-encoded.

With tweaking to switch a couple of characters and remove trailing equals signs, Base64 encoding works well in URLs. Django only needs a couple of lines of code to do this, and here’s what I use in PHP:

function base64UrlEncode($data)
{
  return strtr(rtrim(base64_encode($data), '='), '+/', '-_');
}

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

PHP’s base64_decode doesn’t seem to be fussy if the = padding characters are missing, so the code doesn’t bother to reinstate them.

Using this approach, an SHA1 hash (fed in as binary) ends up as 27 characters instead of 40 for hex, and strings containing multi-byte Unicode characters are kept tidy.


Comments


Comments are now closed for this entry.