Last active
July 2, 2023 20:17
-
-
Save BurakBoz/97fa1adb05f4742bfc489ecc3d6190da to your computer and use it in GitHub Desktop.
RFC Compliant URL Safe Base64 Encode and Decode functions for php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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