Please use Iridium security library instead.
Encodes data to Base64 URL-safe way and decodes encoded data.
This library requires PHP 7.3 or above.
Install via Composer:
composer require oire/base64
Run ./vendor/bin/phpunit
in the project directory.
If you want a version compatible with PHP 7.1.2, please install version 1 instead:
composer require "oire/base64 ^1"
use Oire\Base64\Base64;
use Oire\Base64\Exception\Base64Exception;
$text = "The quick brown fox jumps over the lazy dog";
$encoded = Base64::encode($text);
echo $encoded.PHP_EOL;
This will output:
VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZw
By default, the encode()
method truncates padding =
signs as PHP’s built-in decoder handles this correctly. However, if the second parameter is given and set to true
, =
signs will be replaced with tildes (~
), i.e.:
$encoded = Base64::encode($text, true);
echo $encoded.PHP_EOL;
This will output:
VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZw~~
To decode the data, simply call Base64::decode()
:
$encoded = "VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZw";
try {
$decoded = Base64::decode($encoded);
} catch(Base64Exception $e) {
// Handle errors
}
echo $decoded.PHP_EOL;
This will output:
The quick brown fox jumps over the lazy dog
Copyright © 2017-2021, Andre Polykanine also known as Menelion Elensúlë, The Magical Kingdom of Oirë.
This software is licensed under an MIT license.