note 118051 added to function.base64-encode

From: Date: Fri, 25 Sep 2015 05:26:51 +0000
Subject: note 118051 added to function.base64-encode
Groups: php.notes 
Request: Send a blank email to php-notes+get-203851@lists.php.net to get a copy of this message
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, "._-"); ?> ---- Server IP: 72.52.91.14 Probable Submitter: 2601:281:c100:65fc:dc13:f48:2192:bea4 ---- Manual Page -- http://php.net/manual/en/function.base64-encode.php Edit -- https://master.php.net/note/edit/118051 Del: integrated -- https://master.php.net/note/delete/118051/integrated Del: useless -- https://master.php.net/note/delete/118051/useless Del: bad code -- https://master.php.net/note/delete/118051/bad+code Del: spam -- https://master.php.net/note/delete/118051/spam Del: non-english -- https://master.php.net/note/delete/118051/non-english Del: in docs -- https://master.php.net/note/delete/118051/in+docs Del: other reasons-- https://master.php.net/note/delete/118051 Reject -- https://master.php.net/note/reject/118051 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#203851) next »