PHP has two built-in functions: base64_encode(string $string): string and base64_decode(string $string, bool $strict = false): string|false. PHP strings are byte arrays, so there is no separate Unicode step: UTF-8 text goes in and comes out unchanged.
Basic usage
<?php
echo base64_encode('Grüße 👋'); // R3LDvMOfZSDwn5GL
echo base64_decode('R3LDvMOfZSDwn5GL'); // Grüße 👋
Always use strict mode for untrusted input
Without $strict, base64_decode silently drops invalid characters, so base64_decode('@@@SGVsbG8') returns "Hello". With true, it returns false for anything outside the alphabet:
$data = base64_decode($input, true);
if ($data === false) {
http_response_code(400);
exit('Invalid Base64');
}
Note that strict mode still accepts whitespace and missing padding. For a complete check, compare a round trip:
function is_base64(string $s): bool {
$d = base64_decode($s, true);
return $d !== false && base64_encode($d) === $s;
}
URL-safe Base64
function base64url_encode(string $data): string {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
function base64url_decode(string $data): string|false {
return base64_decode(strtr($data, '-_', '+/'), true);
}
Embed an image as a data URI
$path = 'images/logo.png';
$mime = mime_content_type($path);
$src = 'data:' . $mime . ';base64,' . base64_encode(file_get_contents($path));
echo '<img src="' . $src . '" alt="Logo">';
Save a Base64 upload to a file
if (preg_match('/^data:(image\/(png|jpe?g|webp));base64,/', $dataUri, $m)) {
$bytes = base64_decode(substr($dataUri, strpos($dataUri, ',') + 1), true);
if ($bytes !== false && getimagesizefromstring($bytes)) {
file_put_contents(uniqid('img_', true) . '.' . ($m[2] === 'jpeg' ? 'jpg' : $m[2]), $bytes);
}
}
Never trust the MIME type in the data URI alone; verify the decoded bytes (as getimagesizefromstring does above) before saving.
Line breaks for e-mail
MIME requires lines of at most 76 characters:
$body = chunk_split(base64_encode($attachment)); // 76 chars + "\r\n"
Check your output with the Base64 decoder, or fix broken values with the repair tool.
Kommentare (0)
Fragen, Ideen oder ein Fehler in „Base64 in PHP“? Schreib einen Kommentar, bewerte das Tool oder antworte anderen.
Noch keine Kommentare. Teile als Erste(r) dein Feedback!