PHP URL Friendly Base64 Encode and Decode

Php URL Dostu Base64 Encode - Decode

PHP URL Friendly Base64 Encode and Decode

 Hello friends, today I will show you a function you can use to encode and decode URL-friendly base64.

Sometimes we may prefer to use base64 when we want to send a simple encrypted URL, but there are 2 characters in base64 that can negatively affect our plans and prevent the URL from working. Let's see how we can use base64 in a URL without encountering this issue.

function Base64Encoder($data){
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); 
}

function Base64Decoder($data){
    return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT)); 
}

With the help of the two functions you see above, we can now encode and decode base64 as a URL on our websites.

If we talk about how the functions above work, it is related to the characters used in base64 encoding.

In base64 encoding, a total of 65 characters can be used; these are: 26 lowercase letters + 26 uppercase letters and 10 digits. In addition, "+", "/", and "=" are also used, thus completing the 65 characters. However, if we use these last 3 characters, we get an error because of the URL structure. That's why, when we replace these 3 characters with "-" and "_", our URLs work smoothly.