update page now

Voting

: six minus five?
(Example: nine)

The Note You're Voting On

Anonymous
10 years ago
Wikipedia has a list of 8 or so variations on the last 2 characters in Base64  (https://en.wikipedia.org/wiki/Base64). The following functions can handle all of them:

<?php
function base64_encode2($data, $a = "+/=") {
    $l = strlen($a);
    if ($l === 3) {
        return strtr(base64_encode($data), "+/=", $a);
    } else if ($l === 2) {
        return rtrim(strtr(base64_encode($data), "+/", $a), '=');
    } else {
        throw new InvalidArgumentException("Argument #2 must be 2 or 3 bytes.");
    }
}

function base64_decode2($data, $strict = false, $a = "+/=") {
    $l = strlen($a);
    if ($l === 3) {    
        return base64_decode(strtr($data, $a, "+/="), $strict);
    } else if ($l === 2) {
        return base64_decode(strtr($data, $a, "+/"), $strict);
    } else {
        throw new InvalidArgumentException("Argument #2 must be 2 or 3 bytes.");
    }
}
?>

Example usage:

<?php
$decoded = "ABC123";

// base64 XML identifier:
$encoded = base64_encode2($decoded, "_:");
$decoded = base64_decode2($encoded, false, "_:");

// base64 URL (RFC 6920):
// base64 XML name token:
$encoded = base64_encode($decoded, "-_")
$decoded = base64_decode($encoded, false, "-_");

// modified base64 XML name token:
$encoded = base64_encode2($decoded, ".-");
$decoded = base64_decode2($encoded, false, ".-");

// modified base64 for Regular Expressions:
$encoded = base64_encode2($decoded, "!-");
$decoded = base64_decode2($encoded, false, "!-");

// base64 used in YUI library:
$encoded = base64_encode2($decoded, "._-");
$decoded = base64_decode2($encoded, false, "._-");
?>

<< Back to user notes page

To Top