Skip to main content

Base64 Encoding in PHP: base64_encode() Guide

Learn PHP Base64 encoding with base64_encode() and base64_decode(). Examples for file encoding, data URIs, email attachments, and API auth.

How to Base64 Encode in PHP

PHP provides two built-in functions for Base64: base64_encode() converts binary data to a Base64 string, and base64_decode() reverses it. Unlike JavaScript, PHP handles binary strings natively, so there are no Unicode complications.

Basic Usage

<?php
// Encode to Base64
$encoded = base64_encode(\"Hello, World!\");
echo $encoded; // SGVsbG8sIFdvcmxkIQ==

// Decode from Base64
$decoded = base64_decode(\"SGVsbG8sIFdvcmxkIQ==\");
echo $decoded; // Hello, World!

// Strict mode — returns false on invalid characters
$result = base64_decode(\"invalid!@#\", true);
if ($result === false) {
    echo \"Invalid Base64 input\";
}

Encoding Files and Images

<?php
// Encode an image file
$imageData = file_get_contents(\"photo.jpg\");
$base64Image = base64_encode($imageData);

// Create a data URI for inline HTML images
$mimeType = mime_content_type(\"photo.jpg\");
$dataUri = \"data:{$mimeType};base64,{$base64Image}\";
echo \"<img src='{$dataUri}' alt='Embedded image'>\";

// Decode and save to file
$decoded = base64_decode($base64Image);
file_put_contents(\"output.jpg\", $decoded);

Email Attachments with Base64

MIME email attachments use Base64 encoding. PHP's chunk_split() formats the output to the 76-character line length required by the MIME standard:

<?php
$file = file_get_contents(\"document.pdf\");
$encoded = chunk_split(base64_encode($file));

$headers = \"Content-Type: application/pdf; name=\\\"document.pdf\\\"\\
\";
$headers .= \"Content-Transfer-Encoding: base64\\
\";
$headers .= \"Content-Disposition: attachment; filename=\\\"document.pdf\\\"\\
\";

API Authentication

<?php
// HTTP Basic Auth header
$username = \"api_user\";
$password = \"api_secret\";
$credentials = base64_encode(\"{$username}:{$password}\");

$ch = curl_init(\"https://api.example.com/data\");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    \"Authorization: Basic {$credentials}\"
]);
$response = curl_exec($ch);

Common Use Cases in PHP

  • Data URIs — embed small images directly in HTML without separate HTTP requests
  • Session tokens — encode serialized session data for cookie storage
  • API payloads — transmit binary data through JSON API responses
  • Database storage — store binary objects as text in VARCHAR or TEXT columns

Try Base64 Encoder/Decoder Free

Encode and decode Base64 strings.

Use Base64 Encoder/Decoder →