I have a base64 encoded png, how do I write the image to a file in PHP?

I have a base64 encoded png, how do I write the image to a file in PHP?

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

Stefan Bogdanescu

Founder & Senior Architect

Decoding Base64 PNGs in PHP: Direct Write vs. GD Library

When you receive a string like iVBORw0KGgoAAAANSUhEUg... and need it to become an actual .png file on disk, the instinct is often to skip the decoding step entirely. It feels efficient to treat the base64 string as a binary blob and write it straight to file_put_contents. While this approach works perfectly fine in most scenarios, understanding why it works and when you actually need to decode is critical for writing robust backend code.

The short answer is: You do not need to decode base64 strings if your goal is simply to persist the file.

Base64 encoding is a text-friendly representation of binary data. It maps every 3 bytes of binary input into 4 characters of ASCII output, adding padding characters (=) as needed. Crucially, this process is lossless and reversible only when you intend to recover the original binary stream. However, if your application logic treats that base64 string merely as a container for image data destined for storage, you can write it directly.

Here is how you handle the direct write approach, which matches the snippet you were investigating:

$filename = '/tmp/' . $_REQUEST['id'] . '.png';
$data = $_REQUEST['data'];

// Write directly to disk
file_put_contents($filename, $data);

This code assumes that $_REQUEST['data'] contains the raw base64 string. When PHP's file_put_contents function receives this string, it treats it as a sequence of characters (bytes). Since the operating system stores files in bytes, writing the character representation of the base64 data directly to the file results in a valid file where the contents are that base64 text.

Wait, isn't that wrong? That creates a text file containing base64, not an image. Yes, and that is the crucial distinction. If you write the base64 string directly, you end up with a file whose MIME type would be text/plain (or similar), not image/png. The browser or an image viewer trying to open this file would see gibberish because it expects binary PNG headers but finds ASCII text instead.

To create a usable image file where software can actually render the picture, you must decode the base64 string back into its original binary form before writing. This is where the confusion often lies. The source code snippet you found likely worked for "storing" the data in a way that another script could re-encode or manipulate as text, but it did not create a valid image file.

To generate a true PNG file, you must first convert the base64 string back to binary using base64_decode():

$filename = '/tmp/' . $_REQUEST['id'] . '.png';
$encodedData = $_REQUEST['data'];

// Decode the base64 string back into raw binary
$rawBinary = base64_decode($encodedData);

// Write the raw binary to disk
file_put_contents($filename, $rawBinary);

The base64_decode function transforms the ASCII characters back into the original byte sequence. The resulting $rawBinary variable contains the actual PNG signature (\x89PNG\r\n\x1a\n) and all subsequent image data. Writing this to the file ensures that any client or tool reading the file interprets it correctly as an image.

Why Use the GD Library?

You asked if you should be using the GD library. In this specific context—converting a base64 string to a file—you generally should not use GD unless you need to manipulate the image (e.g., resize, crop, or add watermarks).

Using GD for simple decoding adds unnecessary overhead. The GD library is designed for creating images from scratch (drawing rectangles, loading from URLs) or performing pixel-level manipulation. It involves initializing a resource, handling memory buffers, and potentially re-encoding the data if you pass it through GD functions. If your input is a base64 string representing an existing image, decoding it directly via base64_decode preserves the original compression and metadata perfectly.

Security and Validation Pitfalls

Before writing the file, always validate the input. A malformed base64 string will cause base64_decode to return false, resulting in a file with incorrect content or a PHP warning. Additionally, ensure the filename does not allow directory traversal attacks by sanitizing $id.

If you are working within a Laravel application, consider utilizing Laravel's built-in helpers or storage facade if you need to move files outside the web root, but the core logic of base64_decode remains the same. For production environments, always set appropriate permissions on the output directory and consider implementing strict validation on the MIME type of the decoded data if you are ingesting user uploads.

The choice between direct text storage and binary decoding depends entirely on your downstream usage. If you need a real image file, decode first. If you are storing a record for later re-encoding or transmission over an HTTP header that requires ASCII characters (like application/json responses), keeping it as base64 might be appropriate.

Our network