Get the file extension of a base64 encoded string

Get the file extension of a base64 encoded string

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Inferring File Extensions from Base64 Image Data

When you receive an image as a raw Base64 string via a POST request, determining its file extension isn't immediately obvious because the MIME type and the filename are stripped away during the encoding process. Since you cannot rely on $_FILES data when the upload logic bypasses standard form handling, you must analyze the binary content itself to identify the format.

The most reliable way to distinguish between common image formats like JPEG, PNG, or GIF is by inspecting their magic numbers—specific byte sequences that appear at the very beginning of the file. Base64 encoding adds a 4-character header (data:image/...;base64,) and appends newlines every 76 characters, but the underlying binary signature remains intact within the decoded string.

Decoding Before Analysis

You cannot check for magic bytes directly against the Base64 string because the character set used for encoding (A-Z, a-z, 0-9, +, /) does not align with binary signatures. For instance, a JPEG file starts with FF D8 FF. If you try to search for this pattern in the Base64 string without decoding it first, your regex or string comparison will fail.

The necessary first step is to decode the string into raw binary data. In PHP, base64_decode() handles this transformation efficiently:

$base64_encoded_string = $_POST['image_base64_string'];

// Ensure the string ends cleanly without trailing newline characters if present
if (substr($base64_encoded_string, -1) === "\n") {
    $base64_encoded_string = substr($base64_encoded_string, 0, -1);
}

$rawData = base64_decode($base64_encoded_string);

Once you have the $rawData as a binary string, you can inspect its first few bytes to determine the format.

Checking Magic Bytes for Image Formats

Different image formats have distinct signatures at the start of their binary stream. You can use substr() to extract these bytes and compare them against known patterns.

JPEG files typically begin with FF D8 FF. In hexadecimal notation, this is often represented as 0xFFD8FF.
PNG files always start with a specific 8-byte signature: 89 50 4E 47 0D 0A 1A 0A (which translates to \x89PNG\r\n\x1a\n).
GIF files are identified by the ASCII string GIF89a or GIF87a.

Here is a practical approach using a conditional check based on these signatures:

$extension = null;

// Check for JPEG signature (FF D8)
if (substr($rawData, 0, 2) === "\xFF\xD8") {
    $extension = 'jpg';
} 
// Check for PNG signature (\x89PNG...)
elseif (substr($rawData, 0, 8) === "\x89PNG\r\n\x1a\n") {
    $extension = 'png';
} 
// Check for GIF signature
elseif (substr($rawData, 0, 6) === "GIF") {
    $extension = 'gif';
}

if ($extension === null) {
    // Handle other formats or unsupported types
    throw new InvalidArgumentException('Unsupported image format detected.');
}

Handling the Base64 Header

A common pitfall occurs if the input string includes the data:image/jpeg;base64, prefix. While base64_decode() generally handles this gracefully by ignoring characters outside the base64 alphabet, it is safer to strip the header explicitly before decoding to avoid potential errors or unexpected behavior depending on the PHP version and specific encoding variations.

You can use a regular expression to extract only the Base64 payload:

$payload = preg_replace('/^data:[^;]+\/[^;]+;base64,/', '', $base64_encoded_string);
$rawData = base64_decode($payload);

Why This Approach Works

Relying on magic bytes is superior to guessing based on file size or heuristic analysis. Some image editors or scripts might rename a JPEG file to .png without converting the actual data, leading to corrupted files if you trust the extension blindly. By inspecting the binary header, you ensure that the inferred extension matches the actual content.

This method also scales well for other media types. If you ever need to detect WebP or BMP images later, you simply add another condition checking their respective magic numbers (0x474946 for GIF is GIF, while WebP starts with RIFF...WEBP). The logic remains consistent regardless of the encoding format used to transmit the file.

Our network