How to Base64 Encode Files in PHP

Published on March 12, 2026 · 5 min read

Base64 encoding is incredibly common in backend development, especially when working with file uploads, APIs, or storing image data directly in the database. In PHP, working with Base64 is straightforward thanks to built-in functions.

The Basics: base64_encode()

PHP provides the base64_encode() and base64_decode() functions to handle data conversion. Here's a simple string example:

<?php
$string = "Hello, World!";
$encoded = base64_encode($string);
echo $encoded; // Outputs: SGVsbG8sIFdvcmxkIQ==
?>

Encoding Files and Images

To encode a file (like an image), you first need to read the file's binary contents into memory using file_get_contents(), and then pass that data to the encoder.

<?php
$path = 'uploads/profile_pic.jpg';
$data = file_get_contents($path);
$base64 = base64_encode($data);

echo "Successfully encoded " . strlen($base64) . " characters.";
?>

Generating a HTML Data URI

If you want to display the encoded image directly in an HTML <img> tag, you need to format it as a Data URI. This requires knowing the file's MIME type.

<?php
$path = 'uploads/profile_pic.jpg';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

// Output an image tag
echo '<img src="' . $base64 . '" alt="Profile Picture" />';
?>

Note: While pathinfo() works for trusted files, if you are processing user-uploaded files, you should use mime_content_type() or the finfo class to securely determine the true MIME type to prevent malicious uploads.

Best Practices & Performance

Keep in mind that Base64 encoding increases file size by roughly 33%. Loading large files into memory via file_get_contents() can easily exceed your PHP script's memory limit (often set to 128MB). If you are processing very large videos or zip files, it is better to stream the data or avoid Base64 entirely.

If you're working with Base64-encoded files and need to decode them back, try our Base64 to File converter — it auto-detects the MIME type and lets you download the decoded file. For images specifically, the Image to Base64 tool handles conversion in your browser without any PHP setup.