PHP base64_encode: Encode Binary Data to String

This article explains how to convert binary data into a readable ASCII string using the base64_encode() function in PHP. You will learn the basic syntax of the function, see practical code examples for encoding both text and binary files (like images), and understand how to safely transmit this encoded data across text-only protocols.

What is base64_encode()?

The base64_encode() function is a built-in PHP function used to encode data with MIME base64. This encoding is designed to make binary data survive transport through transport layers that are not 8-bit clean, such as mail bodies. Base64-encoded data takes up about 33% more space than the original data.

Syntax

base64_encode(string $string): string

Example 1: Encoding a Basic String

You can pass any standard string to the function to convert it into a base64 representation.

<?php
$data = "Hello World!";
$encodedData = base64_encode($data);

echo $encodedData; 
// Output: SGVsbG8gV29ybGQh
?>

Example 2: Encoding a Binary File (Image)

One of the most common use cases for base64_encode() is converting binary files, such as images or PDFs, into strings. This allows you to embed files directly into HTML or JSON payloads.

Here is how you can read a binary image file and encode it:

<?php
// Path to your binary file
$filePath = 'logo.png';

// Read the file content into a binary string
$binaryData = file_get_contents($filePath);

if ($binaryData !== false) {
    // Encode the binary data to a base64 string
    $base64String = base64_encode($binaryData);
    
    // Display the base64 string (truncated for readability)
    echo substr($base64String, 0, 50) . '...';
} else {
    echo "Failed to read the file.";
}
?>

Using the Encoded Binary in HTML

Once an image is encoded into a base64 string, you can embed it directly inside an HTML image tag using the Data URI scheme:

<?php
$imageType = pathinfo($filePath, PATHINFO_EXTENSION);
echo '<img src="data:image/' . $imageType . ';base64,' . $base64String . '" />';
?>

How to Decode the Data

To convert the base64 string back into its original binary format, use the companion function base64_decode():

<?php
$encodedString = "SGVsbG8gV29ybGQh";
$originalBinary = base64_decode($encodedString);

echo $originalBinary; 
// Output: Hello World!
?>