PHP Secure URL String base64 Encoding and Decoding

  • 2021-07-01 06:53:04
  • OfStack

If you use the base64_encode and base64_decode methods directly, the resulting string may not be applicable to the URL address. The following methods can solve this problem:

URL Secure String Encoding:


function urlsafe_b64encode($string) {
   $data = base64_encode($string);
   $data = str_replace(array('+','/','='),array('-','_',''),$data);
   return $data;
 }


URL Secure String Decoding:


function urlsafe_b64decode($string) {
   $data = str_replace(array('-','_'),array('+','/'),$string);
   $mod4 = strlen($data) % 4;
   if ($mod4) {
       $data .= substr('====', $mod4);
   }
   return base64_decode($data);
 }


Related articles: