Base64 Encoding
Encodes data with MIME base64. This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies.
function Encode($data)
{
$length; $length2;
$blockCount;
$paddingCount;
$length = strlen($data);
if (($length % 3) == 0)
{
$paddingCount = 0;
$blockCount = floor($length / 3);
}
else
{
$paddingCount = 3 - ($length % 3);
$blockCount = floor(($length + $paddingCount) / 3);
}
$length2 = $length + $paddingCount;
$source2 = array();
for ($x = 0; $x < $length2; $x++)
{
if ($x < $length)
{
$source2[$x] = ord($data[$x]);
}
else
{
$source2[$x] = 0;
}
}
$b1; $b2; $b3;
$temp; $temp1; $temp2; $temp3; $temp4;
$buffer = array();
$result = array();
for ($x = 0; $x < $blockCount; $x++)
{
$b1 = $source2[$x * 3];
$b2 = $source2[$x * 3 + 1];
$b3 = $source2[$x * 3 + 2];
$temp1 = (($b1 & 252) >> 2);
$temp = (($b1 & 3) << 4);
$temp2 = (($b2 & 240) >> 4);
$temp2 += $temp;
$temp = (($b2 & 15) << 2);
$temp3 = (($b3 & 192) >> 6);
$temp3 += $temp;
$temp4 = ($b3 & 63);
$buffer[$x * 4] = $temp1;
$buffer[$x * 4 + 1] = $temp2;
$buffer[$x * 4 + 2] = $temp3;
$buffer[$x * 4 + 3] = $temp4;
}
for ($x = 0; $x < $blockCount * 4; $x++)
{
$result[$x] = SixBitToChar($buffer[$x]);
}
switch ($paddingCount)
{
case 0:
break;
case 1:
$result[$blockCount * 4 - 1] = '=';
break;
case 2:
$result[$blockCount * 4 - 1] = '=';
$result[$blockCount * 4 - 2] = '=';
break;
default:
break;
}
return implode("", $result);
}
function SixBitToChar($b)
{
$lookupTable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
if (($b >= 0) && ($b <= 63))
{
return $lookupTable[$b];
}
else
{
return ' ';
}
}
Example
$data = "jdfgsdhfsdfsd 6445dsfsd7fg/*/+bfjsdgf%$^";
$value = Encode($data, strlen($data));
Output
amRmZ3NkaGZzZGZzZCA2NDQ1ZHNmc2Q3ZmcvKi8rYmZqc2RnZiUkXg==