Base64URL Encode and Decode using PHP

base64_encode & base64_decode functions with custom code

While PHP does support standard Base64 encoding, it does not have built-in support for Base64URL encoding. To achieve that, custom code is required. The code snippet defines two functions to encode and decode a string using Base64URL encoding.

The base64UrlEncode function takes a string as input and returns the Base64URL encoded string. It first encodes the input string using the built-in base64_encode function, which produces a Base64-encoded string. It then replaces the + and / characters with - and _, respectively, using the strtr function. The resulting string is returned after removing any trailing = characters with rtrim.

The base64UrlDecode function takes a Base64URL encoded string as input and returns the decoded string. It first replaces the - and _ characters in the input string with + and /, respectively, using strtr. It then decodes the resulting string using the built-in base64_decode function.

The script then defines a variable and encodes it using the base64UrlEncode function. Next, the encoded string is decoded using base64UrlDecode. Results are printed to the console using echo and PHP_EOL (which inserts a newline character).

<?php

function base64UrlEncode(string $data): string
{
    $base64Url = strtr(base64_encode($data), '+/', '-_');

    return rtrim($base64Url, '=');
}

function base64UrlDecode(string $base64Url): string
{
    return base64_decode(strtr($base64Url, '-_', '+/'));
}

$text = '<<<?!?!?>>>';
$base64Url = base64UrlEncode($text);
echo $base64Url.PHP_EOL;

$text = base64UrlDecode($base64Url);
echo $text.PHP_EOL;

The 1 Comment Found

Leave a Comment

Cancel reply

Your email address will not be published.