Base64 in PHP

Last updated: February 2026

How to encode and decode Base64 in PHP using built-in functions

How Do You Encode a String to Base64 in PHP?

Use base64_encode() to convert a string to Base64. This built-in function accepts a raw string and returns the Base64-encoded representation using the standard alphabet (A-Z, a-z, 0-9, +, /) with = padding. It has been available since PHP 4 and requires no extensions or packages.

<?php
$original = "Hello, World!";
$encoded = base64_encode($original);
echo $encoded; // SGVsbG8sIFdvcmxkIQ==

PHP strings are byte sequences, so base64_encode() works directly on any string content, including binary data and UTF-8 text. No character encoding conversion is needed before encoding. For background on the Base64 format, see What is Base64?. To encode text without writing code, use the Base64 text encoder.

How Do You Decode Base64 in PHP?

Use base64_decode() to convert a Base64 string back to its original data. The function returns the decoded string on success or false on failure. Pass true as the second argument to enable strict mode, which rejects input containing characters outside the Base64 alphabet.

<?php
// Basic decoding
$decoded = base64_decode("SGVsbG8sIFdvcmxkIQ==");
echo $decoded; // Hello, World!

// Strict mode: returns false for invalid input
$result = base64_decode("not valid!@#", true);
if ($result === false) {
    echo "Invalid Base64 input";
}

Without strict mode, base64_decode() silently ignores characters outside the Base64 alphabet. Strict mode is recommended for user-supplied input to detect corrupted or malicious data. Always check the return value against false using the identical operator (===) because a valid decoded string could be falsy. To decode Base64 interactively, use the Base64 text decoder.

How Do You Encode a File to Base64 in PHP?

Read the file contents with file_get_contents() and pass the result to base64_encode(). This loads the entire file into memory as a string. For images, prepend the MIME type to create a data URI suitable for embedding in HTML <img> tags or CSS.

<?php
// Encode a file to Base64
$fileData = file_get_contents("image.png");
$encoded = base64_encode($fileData);

// Create a data URI for HTML embedding
$mimeType = mime_content_type("image.png");
$dataUri = "data:{$mimeType};base64,{$encoded}";
echo '<img src="' . $dataUri . '" alt="Embedded image">';

The mime_content_type() function detects the MIME type automatically. For large files, be aware that file_get_contents() loads the entire file into memory and base64_encode() creates a string approximately 33% larger. Adjust memory_limit accordingly. The Base64 file encoder performs file encoding directly in your browser without uploading to a server.

How Do You Handle Base64 File Uploads in PHP?

Extract the Base64 data from the data URI string, decode it, and save to disk. Data URIs follow the format data:[mime];base64,[data]. Split on the comma to isolate the Base64 payload, decode with base64_decode(), then write the binary data with file_put_contents().

<?php
// Receive a data URI from a form or API request
$dataUri = $_POST['image']; // "data:image/png;base64,iVBORw0KGgo..."

// Extract MIME type and Base64 data
list($header, $base64Data) = explode(',', $dataUri, 2);

// Extract MIME type from header
preg_match('/data:([^;]+);base64/', $header, $matches);
$mimeType = $matches[1]; // "image/png"

// Decode and save the file
$fileData = base64_decode($base64Data, true);
if ($fileData === false) {
    die("Invalid Base64 data");
}
file_put_contents("uploads/image.png", $fileData);

Always validate the MIME type against an allowlist before saving. Never trust the MIME type from the data URI header alone; use finfo_buffer() on the decoded bytes to verify the actual file type. For a complete reference on data URI structure and usage, see the data URI guide.

What PHP Base64 Functions Are Available?

PHP provides 2 core Base64 functions and a helper function for formatting MIME-encoded output. The table below lists each function with its parameters, return type, and use case.

FunctionParametersReturnsDescription
base64_encode($data)string $datastringEncodes data to Base64 (RFC 4648 §4)
base64_decode($data, $strict)string $data, bool $strict = falsestring|falseDecodes Base64 data; returns false on failure in strict mode
chunk_split($string, $length, $separator)string $string, int $length = 76, string $separator = "\r\n"stringSplits a string into chunks; used for MIME formatting

Use chunk_split(base64_encode($data)) to produce MIME-formatted Base64 output with line breaks every 76 characters, as required by RFC 2045 for email attachments. PHP also supports Base64 stream filters via stream_filter_append($stream, 'convert.base64-encode') for processing large data without loading it entirely into memory.

How Do You Validate Base64 in PHP?

Combine strict mode decoding with a regex check for reliable validation. The base64_decode($data, true) strict mode rejects non-alphabet characters but does not verify structural correctness. Add a regex pattern to confirm the string matches the expected Base64 format before decoding.

<?php
function isValidBase64(string $data): bool {
    // Check for valid Base64 characters and correct padding
    if (!preg_match('/^[A-Za-z0-9+\/]*={0,2}$/', $data)) {
        return false;
    }
    // Length must be a multiple of 4
    if (strlen($data) % 4 !== 0) {
        return false;
    }
    // Attempt strict decode
    return base64_decode($data, true) !== false;
}

echo isValidBase64("SGVsbG8=") ? "valid" : "invalid"; // valid
echo isValidBase64("not!valid") ? "valid" : "invalid"; // invalid

The regex /^[A-Za-z0-9+\/]*={0,2}$/ ensures only valid Base64 characters are present and that padding uses at most 2 = characters. The length check confirms proper 4-character grouping. For browser-based validation without writing PHP, use the Base64 validator. For URL-safe Base64 validation, adjust the regex to accept - and _ instead of + and /; see the URL-safe Base64 tool.

Frequently Asked Questions

Does PHP have built-in Base64 support?

Yes. PHP includes base64_encode() and base64_decode() as built-in functions available since PHP 4. No extension, composer package, or additional configuration is required. These functions are part of PHP's core and are always available in every PHP installation.

How do you validate Base64 input in PHP?

Pass true as the second argument to base64_decode($data, true) to enable strict mode. In strict mode, the function returns false if the input contains characters outside the Base64 alphabet (A-Z, a-z, 0-9, +, /, =). Without strict mode, invalid characters are silently discarded. Combine with a regex check for complete validation.

How does PHP handle large files with Base64?

base64_encode() loads the entire file into memory as a string. For large files, this may exceed PHP's memory_limit. Increase the limit with ini_set('memory_limit', '256M') or use stream filters with stream_filter_append($handle, 'convert.base64-encode') to process files in chunks without loading everything into memory.

How do you create URL-safe Base64 in PHP?

PHP does not have a dedicated URL-safe Base64 function. Encode with base64_encode(), then replace + with -, / with _, and optionally remove = padding using strtr() and rtrim(). To decode, reverse the character replacement with strtr() and pass the result to base64_decode(). See the URL-safe Base64 tool for browser-based encoding.

How do you decode a Base64 image in PHP?

Extract the Base64 data from the data URI by splitting on the comma with explode(',', $dataUri, 2), then pass the second element to base64_decode(). Write the decoded bytes to a file with file_put_contents() or process them with GD (imagecreatefromstring()) or Imagick. Always validate the decoded data with finfo_buffer() before saving. For browser-based image encoding, use the Base64 image encoder.

Related Base64 Tools and Guides