32 lines
1.1 KiB
PHP
32 lines
1.1 KiB
PHP
<?php
|
|
// UriBase64.php
|
|
// Created: 2022-01-13
|
|
// Updated: 2024-07-31
|
|
|
|
namespace Index;
|
|
|
|
/**
|
|
* Provides URL-safe Base64 encoding.
|
|
*/
|
|
final class UriBase64 {
|
|
/**
|
|
* Encodes data with URI-safe MIME base64.
|
|
*
|
|
* @param string $string The data to encode.
|
|
* @return string The encoded data, as a string.
|
|
*/
|
|
public static function encode(string $string): string {
|
|
return rtrim(strtr(base64_encode($string), '+/', '-_'), '=');
|
|
}
|
|
|
|
/**
|
|
* Decodes data encoded with URI-safe MIME base64.
|
|
*
|
|
* @param string $string The encoded data.
|
|
* @param bool $strict If the strict parameter is set to true then the base64_decode() function will return false if the input contains character from outside the base64 alphabet. Otherwise invalid characters will be silently discarded.
|
|
* @return string|false Returns the decoded data or false on failure. The returned data may be binary.
|
|
*/
|
|
public static function decode(string $string, bool $strict = false): string|false {
|
|
return base64_decode(str_pad(strtr($string, '-_', '+/'), strlen($string) % 4, '=', STR_PAD_RIGHT));
|
|
}
|
|
}
|