ApiKey

base64
in package

Class base64: Provides static methods for encoding and decoding strings using a URL-safe variant of Base64. This encoding scheme replaces the standard Base64 characters '+' and '/' with '-' and '_', respectively, and removes any trailing '=' padding characters. This makes the encoded strings suitable for use in URLs and filenames without requiring further encoding.

Tags
since
0.0.1

Table of Contents

Methods

decode()  : string
Converts a URL-safe Base64 string back to its original plain text.
encode()  : string
Converts a plain text string to its URL-safe Base64 representation.
test()  : void
Tests the URL-safe Base64 encoding and decoding methods.

Methods

decode()

Converts a URL-safe Base64 string back to its original plain text.

public static decode(string $base64Url) : string

This method reverses the URL-safe modifications by replacing '-' with '+' and '_' with '/'. It also adds back any necessary '=' padding characters before performing standard Base64 decoding.

Parameters
$base64Url : string

The URL-safe Base64 string to convert.

Tags
example
$urlSafe = "SGVsbG8gV29ybGQh";
$originalText = base64::decode($urlSafe); // Output: Hello World!

$urlSafeSpecial = "U3RyaW5nIHdpdGggLSBhbmQgXw";
$originalTextSpecial = base64::decode($urlSafeSpecial); // Output: String with + and /=
since
0.0.1
Return values
string

The original plain text representation.

encode()

Converts a plain text string to its URL-safe Base64 representation.

public static encode(string $plainText) : string

This method first performs standard Base64 encoding on the input string and then replaces any '+' characters with '-', '/' characters with '_', and removes any trailing '=' padding.

Parameters
$plainText : string

The plain text string to convert.

Tags
example
$text = "Hello World!";
$urlSafeBase64 = base64::encode($text); // Output: SGVsbG8gV29ybGQh

$textWithSpecial = "String with + and /=";
$urlSafeBase64Special = base64::encode($textWithSpecial); // Output: U3RyaW5nIHdpdGggLSBhbmQgXw
since
0.0.1
Return values
string

The URL-safe Base64 representation of the input string.

test()

Tests the URL-safe Base64 encoding and decoding methods.

public static test([bool $debug = false ]) : void

This method performs a series of tests with various input strings, including those with special characters and different padding scenarios, to ensure that the encode() and decode() methods function correctly. It uses PHP's assert() function to verify the expected outcomes.

Parameters
$debug : bool = false

Optional. If set to true, detailed debug information will be displayed for each test case, including the encoded string, the decoded string, and whether the decoded string matches the original. Defaults to false.

Tags
example
base64::test(); // Runs the tests. No output on success, errors on failure.
base64::test(true); // Runs the tests with detailed debug output.
since
0.0.1

        
On this page

Search results