<?php
class PurePHPBase64
{
private const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
private const PADDING = '=';
public static function encode(string $data): string
{
$length = strlen($data);
if ($length === 0) return '';
$encoded = '';
for ($i = 0; $i < $length; $i += 3) {
$b1 = ord($data[$i]);
$b2 = ($i + 1 < $length) ? ord($data[$i + 1]) : 0;
$b3 = ($i + 2 < $length) ? ord($data[$i + 2]) : 0;
$encoded .= self::ALPHABET[$b1 >> 2];
$encoded .= self::ALPHABET[(($b1 & 0x03) << 4) | ($b2 >> 4)];
if ($i + 1 < $length) {
$encoded .= self::ALPHABET[(($b2 & 0x0F) << 2) | ($b3 >> 6)];
} else {
$encoded .= self::PADDING;
}
if ($i + 2 < $length) {
$encoded .= self::ALPHABET[$b3 & 0x3F];
} else {
$encoded .= self::PADDING;
}
}
return $encoded;
}
public static function decode(string $base64, bool $strict = false): string|false
{
if ($strict && preg_match('/[^A-Za-z0-9+\/=\s]/', $base64)) {
return false;
}
$base64 = str_replace([self::PADDING, " ", "\t", "\r", "\n"], '', $base64);
$length = strlen($base64);
if ($length === 0) return '';
$decoded = '';
$map = array_flip(str_split(self::ALPHABET));
for ($i = 0; $i < $length; $i += 4) {
$c1 = isset($base64[$i]) ? $map[$base64[$i]] : 0;
$c2 = isset($base64[$i + 1]) ? $map[$base64[$i + 1]] : 0;
$c3 = isset($base64[$i + 2]) ? $map[$base64[$i + 2]] : 0;
$c4 = isset($base64[$i + 3]) ? $map[$base64[$i + 3]] : 0;
$decoded .= chr(($c1 << 2) | ($c2 >> 4));
if (isset($base64[$i + 2])) {
$decoded .= chr((($c2 & 0x0F) << 4) | ($c3 >> 2));
}
if (isset($base64[$i + 3])) {
$decoded .= chr((($c3 & 0x03) << 6) | $c4);
}
}
return $decoded;
}
}
Fallback codes-
function safe_base64_encode(string $data): string
{
if (function_exists('base64_encode')) {
return base64_encode($data);
}
return PurePHPBase64::encode($data);
}
function safe_base64_decode(string $data, bool $strict = false): string|false
{
if (function_exists('base64_decode')) {
return base64_decode($data, $strict);
}
return PurePHPBase64::decode($data, $strict);
}
Here the best Base64 encode & decode free online tool- https:Also all awesom tools of needlecode team are - https: