Base64 Encoding in PHP
PHP provides simple built-in functions for Base64 encoding and decoding.
Basic Usage
Encode to Base64
<?php
$text = "Hello, World!";
$encoded = base64_encode($text);
echo $encoded; // "SGVsbG8sIFdvcmxkIQ==" Decode from Base64
<?php
$encoded = "SGVsbG8sIFdvcmxkIQ==";
$decoded = base64_decode($encoded);
echo $decoded; // "Hello, World!" Strict Decoding
Use strict mode to return false for invalid Base64:
<?php
$valid = base64_decode("SGVsbG8=", true); // "Hello"
$invalid = base64_decode("Invalid!!!", true); // false
if ($valid === false) {
echo "Invalid Base64";
} URL-Safe Base64
PHP doesn't have built-in URL-safe Base64, but it's easy to implement:
<?php
function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
function base64url_decode($data) {
return base64_decode(strtr($data, '-_', '+/'));
}
$text = "Hello, World!";
$encoded = base64url_encode($text);
$decoded = base64url_decode($encoded);
echo $encoded . "\n";
echo $decoded; File to Base64
Encode a File
<?php
$content = file_get_contents('image.png');
$encoded = base64_encode($content);
echo $encoded; Decode to File
<?php
$encoded = "iVBORw0KGgo..."; // Base64 string
$decoded = base64_decode($encoded);
file_put_contents('output.png', $decoded); Data URL
Create a Data URL from a file:
<?php
function fileToDataUrl($filepath) {
$mime = mime_content_type($filepath);
$data = file_get_contents($filepath);
return "data:$mime;base64," . base64_encode($data);
}
$dataUrl = fileToDataUrl('image.png');
echo $dataUrl; Image from Base64
Display a Base64 image directly in HTML:
<?php
$imageData = file_get_contents('image.png');
$base64 = base64_encode($imageData);
$mime = mime_content_type('image.png');
?>
<img src="data:<?= $mime ?>;base64,<?= $base64 ?>" alt="Image"> Chunked Encoding
For MIME-compatible output with line breaks:
<?php
$text = "Hello, World!";
$encoded = chunk_split(base64_encode($text), 76, "\r\n");
echo $encoded; CLI One-Liner
# Encode
php -r "echo base64_encode('Hello');"
# Decode
php -r "echo base64_decode('SGVsbG8=');"