spomky-labs/base64url
Fast RFC 4648 Base64 URL-safe encoder/decoder for PHP. Lightweight library to encode/decode URL-safe Base64 strings with high performance, compatible with PHP 7.1+. Ideal for JWT, web tokens, and URL parameters.
Installation
composer require spomky-labs/base64url
No additional configuration is required—just autoload the package.
First Use Case Encode a string to Base64URL (e.g., for JWT tokens, API keys, or URL-safe data):
use SpomkyLabs\Base64Url\Base64Url;
$encoder = new Base64Url();
$encoded = $encoder->encode('Hello, World!');
// Output: "SGVsbG8sIFdvcmxkIQ=="
Decode it back:
$decoded = $encoder->decode($encoded);
// Output: "Hello, World!"
Where to Look First
Base64Url::encode() and Base64Url::decode() methods.Base64Url constructor (e.g., padding options).JWT Token Handling
Encode/decode payloads for JWTs (replace base64_encode/base64_decode):
$payload = json_encode(['user_id' => 123, 'role' => 'admin']);
$encodedPayload = $encoder->encode($payload);
// Use $encodedPayload in JWT generation (e.g., with `firebase/php-jwt`).
URL-Safe API Keys
Store or transmit API keys in URLs (e.g., /api/v1?key=ENCODED_KEY):
$apiKey = 'sk_live_123abc';
$safeKey = $encoder->encode($apiKey);
// URL-safe: `/api/v1?key=czsxX3xpdnFfMTIzYWJj`
Database Storage Store binary data (e.g., hashes) in text fields:
$hash = hash('sha256', 'secret');
$dbValue = $encoder->encode($hash);
// Later: $originalHash = $encoder->decode($dbValue);
Laravel Facades (Optional) Create a facade for cleaner syntax:
// app/Providers/AppServiceProvider.php
public function boot()
{
$this->app->bind('base64url', function () {
return new Base64Url();
});
}
Usage:
$encoded = app('base64url')->encode('data');
Service Layer Encapsulate encoding/decoding in a service:
class ApiKeyService {
protected $encoder;
public function __construct(Base64Url $encoder) {
$this->encoder = $encoder;
}
public function generateSafeKey(string $key): string {
return $this->encoder->encode($key);
}
}
Validation Use with Laravel’s validation:
$request->validate([
'encoded_key' => 'required|string',
]);
$decodedKey = $encoder->decode($request->encoded_key);
Padding Handling
= characters) during encoding.$decoded = $encoder->decode($encoded, false); // Skip padding check (not recommended).
str_pad).Non-String Inputs
null, objects) will throw errors.$encoder->encode((string) $variable);
Binary Data
base64_encode first, then this library:
$binaryData = file_get_contents('image.png');
$encoded = $encoder->encode(base64_encode($binaryData));
URL Safety Assumptions
+ with - and / with _, but does not URL-encode other special characters (e.g., ~, ?).rawurlencode:
$safeForUrl = rawurlencode($encoder->encode('key=value'));
Decoding Failures
InvalidArgumentException, check:
[A-Z0-9_-] (Base64URL alphabet).Character Mismatches
base64_encode output to spot discrepancies:
var_dump(
base64_encode('test'), // "dGVzdA=="
$encoder->encode('test') // "dGVzdA==" (should match)
);
Custom Alphabets
class CustomBase64Url extends Base64Url {
protected $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
public function __construct() {
parent::__construct();
$this->setAlphabet($this->alphabet);
}
}
Padding Strategies
$encoder = new Base64Url();
$encoder->setPadding(false); // Disable padding (not recommended for decoding).
Performance
$encoder = new Base64Url(); // Reuse this instance.
Cached Config Store encoded values in config/cache (e.g., API keys):
config(['services.api.key' => $encoder->encode('secret_key')]);
Encrypted Storage Combine with Laravel’s encryption for sensitive data:
$encoded = $encoder->encode('secret');
$encrypted = encrypt($encoded);
How can I help you explore Laravel packages today?