PHP get pdf file from base64 encoded data string

PHP get pdf file from base64 encoded data string

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

Stefan Bogdanescu

Founder & Senior Architect

Converting Base64 PDF Strings to Files in PHP

You often encounter Base64-encoded data when consuming APIs, processing email attachments, or handling file uploads that bypass traditional multipart forms. The core question is straightforward: how do you transform a raw Base64 string into an actual .pdf file on the server filesystem?

The most efficient approach relies on PHP's built-in file_put_contents function combined with base64_decode. You do not need to manually reconstruct the binary stream or manipulate headers unless you are specifically generating a response for HTTP output.

The Core Mechanism

At its simplest, Base64 encoding is an ASCII-safe representation of binary data. To reverse this, you simply decode the string back into binary and write it to disk.

$base64String = 'JVBERi0xLjQKJeLjz9MKNCAwIG9iago8PAovVHlwZSAvUGFnZQovUGFyZW50IDEgMCBSCi9NZWRpYUJveCBbMCAwIDYxMiA3OTJdCi9Db250ZW50cyAyIDAgUgovUmVzb3VyY2VzIDMgMCBSCj4+CmVuZG9iago...'; // Example truncated

// Decode the string
$pdfBinary = base64_decode($base64String);

if ($pdfBinary === false) {
    throw new InvalidArgumentException('Invalid Base64 string');
}

// Write to disk
$filename = 'documents/document.pdf';
if (file_put_contents($filename, $pdfBinary) === false) {
    throw new RuntimeException('Failed to write file');
}

This pattern is robust because it handles the binary conversion internally. The base64_decode function returns a byte string that matches the original PDF structure exactly once decoded. You then pass this binary data directly to file_put_contents. This ensures the resulting file retains its internal headers, metadata, and object definitions without corruption.

Handling HTTP Responses

If your goal is not to save the file but to serve it via an HTTP response, the approach shifts slightly. Here, you must set the correct MIME type in the headers before echoing the decoded content. This mimics what a standard web server does when serving a static resource.

$pdfBinary = base64_decode($base64String);

header('Content-Type: application/pdf');
header('Content-Length: ' . strlen($pdfBinary));
echo $pdfBinary;

Setting Content-Type: application/pdf is critical here. Without it, browsers may attempt to render the PDF as plain text or force a download based on the default content type, depending on user agent behavior. The Content-Length header helps the client understand exactly how much data to expect, ensuring the stream closes correctly.

Security and Validation Pitfalls

When working with Base64 strings from external sources, validation is non-negotiable. A malformed string might result in a warning rather than an error, leaving your application in an uncertain state. Always verify that base64_decode returns false before proceeding. Additionally, check the resulting binary data if possible, though for PDFs specifically, you might verify the magic bytes at the start of the file (%PDF).

$decoded = base64_decode($data);
if ($decoded === false) {
    // Handle error: Invalid input
} elseif (substr($decoded, 0, 4) !== '%PDF') {
    // Handle error: Not a valid PDF
}

Storage Considerations

Writing large Base64 strings to disk requires attention to file system limits and memory usage. Base64 encoding increases data size by approximately 33% because it represents 6 bits of binary data per character. If you are decoding massive files, ensure your web server has sufficient space in the target directory. In high-traffic environments where you process thousands of such requests per minute, consider moving to a streaming approach if supported by the upstream API, rather than buffering the entire decoded string into memory before writing to disk.

For developers seeking further resources on handling file operations or generating dynamic documents within the PHP ecosystem, platforms like https://laravelcompany.com often provide insights into modern frameworks that simplify these tasks, though the native approach remains the most lightweight for simple conversions.

Our network