PHP, display image with Header()

PHP, display image with Header()

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

Stefan Bogdanescu

Founder & Senior Architect

The Content-Type Fallacy: Why readfile Works Without Strict MIME Checks

When serving dynamic images from outside the web root, developers often rely on a two-step pattern: setting the header and reading the file. A common implementation looks like this:

header('Content-type: image/png');
readfile($fullpath);

The confusion usually stems from the explicit image/png declaration. If your script also serves JPEG or GIF files using the exact same logic, you might assume the browser is ignoring your header or that the server is silently correcting the MIME type. Neither is true. The behavior relies on a specific interaction between HTTP headers and browser heuristics, not a magical fallback in PHP itself.

How the Browser Decides What to Render

The core mechanism here is the Content-Type header versus the file extension in the URL. When you send Content-Type: image/png, you are telling the client, "I am about to send data that the browser should interpret as a PNG." If the data arriving matches the PNG specification, the browser renders it perfectly.

If the $fullpath points to a .jpg file, but your header explicitly says image/png, strict browsers will display the image correctly only if they employ content sniffing. Modern web browsers are notoriously lenient when it comes to images. They prioritize the visual output over strict protocol adherence. When a browser receives an image stream, it attempts to read the magic bytes (the file signature) at the beginning of the data.

For JPEGs, these are FF D8 FF. For PNGs, they are 89 50 4E 47. If the header says PNG but the bytes say JPEG, a strict browser might show an error or refuse to render. However, most browsers will ignore the mismatch and rely on the data signature instead. This is why your code appears to work for multiple formats despite the hardcoded image/png header; the user agent is effectively overwriting your instruction based on the file's actual content.

The Risks of Hardcoding MIME Types

While this leniency works for viewing images, hardcoding the MIME type creates significant maintenance and security liabilities.

First, it couples your logic to a specific format that you might not know at runtime. If $fullpath changes from a PNG to a PDF or a plain text file, the browser will attempt to render the image. For supported formats like JPEG, GIF, or WebP, it works. For others, such as HTML or SVG (depending on the browser), you risk breaking layout or rendering unexpected content within an <img> tag context.

Second, and more critically, this approach bypasses Content Security Policy (CSP) protections. If a CSP directive specifies img-src restrictions that exclude certain MIME types, the browser will block the request entirely if it detects a mismatch between the declared type and the sniffed type. Relying on browser sniffing makes your application fragile in strict security environments.

The Robust Approach: Dynamic MIME Types

To build a resilient image serving endpoint, you should determine the MIME type based on the file extension or the actual magic bytes of the file, rather than assuming it is always PNG. PHP provides a reliable way to handle this using the finfo extension, which inspects the file contents directly.

Here is how to dynamically set the header:

// Determine the MIME type based on file content
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($fullpath);

// Only send headers if we have a valid image type
if ($mime && str_starts_with($mime, 'image/')) {
    header("Content-Type: " . $mime);
} else {
    // Handle non-image files or errors appropriately
    http_response_code(400);
    exit('Invalid image file.');
}

readfile($fullpath);

This snippet ensures that regardless of whether the source is a .png, .jpg, .gif, or a future format like .webp or .avif, the server sends the correct Content-Type. It removes the dependency on browser sniffing, ensuring compatibility across all user agents and respecting strict security policies.

When to Use Static Headers

There are scenarios where static headers might still be appropriate. If your application is strictly serving a single image format and you have full control over the file generation process (e.g., always converting uploads to PNG before storage), hardcoding image/png can save a tiny amount of CPU cycles by avoiding the finfo check. However, given that modern PHP execution time is rarely the bottleneck for I/O operations like readfile, the slight overhead of checking the MIME type is negligible compared to the benefits of correctness and security.

In summary, your existing code works because browsers are forgiving, but relying on that forgiveness is a technical debt you should pay off with dynamic MIME detection.

Our network