Skip to content

Instantly share code, notes, and snippets.

@nawawi
Created December 9, 2024 13:25
Show Gist options
  • Save nawawi/f3e2521d2efbaf21239dd9516a860ae8 to your computer and use it in GitHub Desktop.
Save nawawi/f3e2521d2efbaf21239dd9516a860ae8 to your computer and use it in GitHub Desktop.
custom_base64_decode
<?php
function custom_base64_decode($input) {
$base64_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
$output = '';
// Remove padding characters and replace invalid characters
$input = str_replace(['-', '_'], ['+', '/'], $input);
$input = rtrim($input, '=');
$bitstream = '';
foreach (str_split($input) as $char) {
$position = strpos($base64_chars, $char);
if ($position === false) {
throw new InvalidArgumentException("Invalid Base64 character: {$char}");
}
$bitstream .= str_pad(decbin($position), 6, '0', STR_PAD_LEFT);
}
$bytes = str_split($bitstream, 8);
foreach ($bytes as $byte) {
if (strlen($byte) === 8) {
$output .= chr(bindec($byte));
}
}
return $output;
}
// Example usage
$encoded = base64_encode("Hello World");
$decoded = custom_base64_decode($encoded);
echo $decoded;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment