URL-safe base64_encode for PHP

Unbeknownst to many, base64_encode in PHP can generate strings with + and / characters in them. This can then break URLs.

The below snippets are a URL safe base64_encode and base64_decode function that handles this for you.

public static function b64enc($string)
{
    return str_replace(array('+', '/'), array('-', '_'), base64_encode($string));
}

public static function b64dec($string)
{
    return base64_decode(str_replace(array('-', '_'), array('+', '/'), $string));
}

Got Something To Say?

Your email address will not be published. Required fields are marked *