PHP

URL-Safe Base64 Encode / Decode

admin by @admin ADMIN
5h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Standard base64 uses + and / which break in URLs. Swap them for - and _, drop the = padding, and you get a string you can put in path segments and query parameters safely.
PHP
Raw
<?php
function base64UrlEncode(string $bytes): string {
    return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
}

function base64UrlDecode(string $s): string|false {
    $padded = $s . str_repeat('=', (4 - strlen($s) % 4) % 4);
    return base64_decode(strtr($padded, '-_', '+/'), true);
}

$payload = base64UrlEncode(random_bytes(32));
echo $payload;                          // e.g. "X1zR_jc7HpQ..."
$decoded = base64UrlDecode($payload);   // bytes round-trip exactly
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.