Development

Working with Base64 in PHP

Learn how to use base64_encode() and base64_decode() in PHP, including how to safely process URL variants and check for valid encoding.

Published on August 18, 20265 min read

PHP provides two built-in, globally available functions for Base64 conversion: base64_encode() and base64_decode(). These functions are extremely fast and work out-of-the-box on strings.

Strings vs Bytes in PHP

Unlike strongly-typed languages like Java or C#, PHP's string type is essentially a byte array. This means you can pass standard text strings OR raw binary file data directly into base64_encode() without having to cast them to a byte array first.

1. Encode a String in PHP

To encode a standard string, simply pass it to base64_encode().

php
<?php
$text = "Hello, PHP Base64!";

// Encode the string
$encoded = base64_encode($text);

echo $encoded;
// Output: SGVsbG8sIFBIUCBCYXNlNjQh
?>

2. Decode a String in PHP

To decode, use base64_decode(). By default, if the input contains characters outside the Base64 alphabet, PHP will quietly ignore them. If you want strict validation, you must pass true as the second argument.

php
<?php
$encoded = "SGVsbG8sIFBIUCBCYXNlNjQh";

// Standard decode (ignores invalid characters)
$decoded = base64_decode($encoded);
echo $decoded;
// Output: Hello, PHP Base64!

// Strict decode (returns false if input is invalid)
$invalidBase64 = "SGVsbG8sIFBIUCBCYXNlNjQh*#";
$strictDecode = base64_decode($invalidBase64, true);

if ($strictDecode === false) {
    echo "Strict decoding failed: Invalid characters detected.";
}
?>

3. URL-Safe Base64 in PHP

PHP does not have a built-in base64url_encode() function. Since standard Base64 generates + and / (which are reserved in URLs), you need to manually replace these characters using strtr().

php
<?php

function base64url_encode($data) {
    // 1. Encode in standard Base64
    $b64 = base64_encode($data);
    
    // 2. Replace + with - and / with _
    $urlSafe = strtr($b64, '+/', '-_');
    
    // 3. (Optional) Remove the trailing '=' padding
    return rtrim($urlSafe, '=');
}

function base64url_decode($data) {
    // 1. Replace - with + and _ with /
    $b64 = strtr($data, '-_', '+/');
    
    // 2. PHP's base64_decode automatically handles missing padding, 
    // but if you want to be strict, you can re-pad it:
    $padded = str_pad($b64, strlen($b64) % 4, '=', STR_PAD_RIGHT);
    
    return base64_decode($padded, true);
}

$secret = "subjects?dir=/usr/local";
$token = base64url_encode($secret);

echo $token; 
// Output: c3ViamVjdHM_ZGlyPS91c3IvbG9jYWw
?>

Testing PHP Tokens?

If you've generated a Base64URL string in PHP and need to quickly debug or decode it, use our interactive toolkit.

Go to the Base64 Converter Tool