Base64 Encode & Decode in PHP

Encode or decode below — it runs locally in your browser — then grab the canonical PHP code. PHP ships with base64_encode() and base64_decode() built in, so there is nothing to install; the only wrinkle is the URL-safe variant, which needs a manual swap.

INPUT
OUTPUT
Type or paste to encode / decode

Encode and decode a string

Both functions take and return a plain string — no byte handling required:

<?php

// Encode
$encoded = base64_encode("Hello, world!");
echo $encoded; // SGVsbG8sIHdvcmxkIQ==

// Decode
$decoded = base64_decode("SGVsbG8sIHdvcmxkIQ==");
echo $decoded; // Hello, world!

Tip: pass true as the second argument to decode in strict mode — base64_decode($s, true) returns false on invalid input instead of guessing, so always use it when validating untrusted data.

URL-safe Base64

For JWTs, URLs, and filenames, swap +/ for -_ and drop the = padding. PHP has no built-in, so define your own:

<?php

// URL-safe encode, padding stripped
function base64url_encode(string $data): string {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

// URL-safe decode, restoring + / and padding
function base64url_decode(string $data): string|false {
    $padded = strtr($data, '-_', '+/');
    $padded = str_pad($padded, strlen($padded) + (4 - strlen($padded) % 4) % 4, '=');
    return base64_decode($padded, true);
}

echo base64url_encode("Hello, world!"); // SGVsbG8sIHdvcmxkIQ

Encode a file

<?php

$encoded = base64_encode(file_get_contents('img.png'));

// As a data URI for HTML/CSS:
$dataUri = "data:image/png;base64,{$encoded}";

Frequently asked questions

How do I Base64 encode a string in PHP?

Use the built-in base64_encode(): base64_encode("Hello, world!") returns "SGVsbG8sIHdvcmxkIQ==". No import or library is needed.

How do I Base64 decode in PHP?

base64_decode("SGVsbG8sIHdvcmxkIQ==") returns "Hello, world!"; pass true as the second argument to fail on invalid input.

How do I do URL-safe Base64?

Swap the alphabet with strtr($b64, '+/', '-_') and drop padding via rtrim($b64, '='); reverse with strtr($s, '-_', '+/') before decoding.

How do I validate Base64 input in PHP?

Use strict mode: base64_decode($input, true) returns false when the input has characters outside the Base64 alphabet.

Need image, file, or URL-safe modes?

The main base64.dev tool handles text, images, files, and URL-safe Base64 with auto-detect.

Open base64.dev →