Skip to content

Instantly share code, notes, and snippets.

@BurakBoz
Last active July 2, 2023 20:17
Show Gist options
  • Save BurakBoz/97fa1adb05f4742bfc489ecc3d6190da to your computer and use it in GitHub Desktop.
Save BurakBoz/97fa1adb05f4742bfc489ecc3d6190da to your computer and use it in GitHub Desktop.
RFC Compliant URL Safe Base64 Encode and Decode functions for php
<?php
function urlsafe_base64_encode($string)
{
return str_replace(['+','/','='], ['-','_',''], base64_encode($string));
}
function urlsafe_base64_decode($string)
{
$string = str_replace(['-','_'], ['+','/'], $string);
$mod4 = strlen($string) % 4;
if ($mod4) $string .= substr('====', $mod4);
return base64_decode($string);
}
/** test code */
$text = "Smile for me 😃..";
$encode = urlsafe_base64_encode($text);
$decode = urlsafe_base64_decode($encode);
echo "
String: $text
Encoded: $encode
Decoded: $decode
";
if($text == $decode) echo "Validated." . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment