PHP base64 encode and strict decode
PHP
<?php
function b64_encode(string $data): string
{
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
function b64_decode(string $text): string
{
$padded = strtr($text, '-_', '+/');
$padded .= str_repeat('=', (4 - strlen($padded) % 4) % 4);
$decoded = base64_decode($padded, true);
if ($decoded === false) {
throw new InvalidArgumentException('Invalid base64 input');
}
return $decoded;
}