PHP header ('Content-Type: image/png')

PHP header ('Content-Type: image/png')

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

Stefan Bogdanescu

Founder & Senior Architect

PHP header ('Content-Type: image/png')

When you run a script that generates an image on the fly, the browser expects a specific sequence of events. It first checks for the Content-Type header to determine how to render the response. If that header is missing or delayed, the browser treats the output as standard HTML text rather than binary image data. This mismatch often results in the dreaded "broken image" icon appearing in the top-left corner of your viewport.

In your specific case, you are using PHP 5.3.10 with GD support enabled. Your code looks correct at first glance:

<?php
header('Content-Type: image/png');
$im = @imagecreatetruecolor(120, 20) or die('Cannot Initialize new GD image stream');
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);
imagepng($im);
imagedestroy($im);
?>

The logic here is sound. You are setting the header before any output is sent to the browser, and you are flushing the image buffer immediately after imagepng(). However, the symptom you described—where Internet Explorer still receives a "bunch of data" despite the header—points to a subtle interaction between the web server's response buffering and PHP's output handling.

The Buffering Trap

The core issue is not necessarily your PHP code, but rather how the web server (likely Apache or Nginx) handles the response before it reaches the client. When you call header('Content-Type: image/png'), you are telling the HTTP protocol what the payload should be. However, if the web server buffers the entire response in memory before sending it, it may decide to send a "Connection Keep-Alive" header or other metadata that interferes with strict binary data streams.

More critically, if your application environment (or the web server configuration) has output buffering enabled, PHP might not realize that imagepng() has finished writing until the script ends. If any whitespace exists before the opening <?php tag, or if there are hidden characters in a template file included earlier, the header function will fail silently. In PHP 5.3, this failure is particularly insidious because it does not throw a warning by default unless you enable display_errors.

The "bunch of data" you see in IE suggests that the browser is interpreting the image bytes as text. This happens when the Content-Type header is either sent after some other output, or if the server sends an HTTP status code (like 200 OK) followed by content that the client doesn't recognize as a valid PNG stream due to missing headers.

Ensuring Clean Headers

To resolve this, you must guarantee that no characters are sent before the header command. This includes:

  • Whitespace or newlines before <?php.
  • Echo statements or print functions prior to header().
  • Output from included files (like .htaccess rules that might trigger redirects).

If you are using a framework or a template engine, ensure that no HTML is echoed before the image generation logic runs. One robust pattern is to wrap your image generation in a function that explicitly checks for headers:

function sendImage($path) {
    if (!headers_sent()) {
        header('Content-Type: image/png');
    }
    
    // Ensure we don't accidentally flush earlier output
    ob_flush(); 
    flush();

    // Read and echo the file or generate stream
    readfile($path); 
}

In your specific script, imagepng() writes directly to the output buffer. If your web server is configured to compress responses (gzip) by default, it might try to wrap your PNG data in a gzip stream before sending it. Browsers expect raw PNG data when you specify image/png. If the server sends Content-Encoding: gzip, the browser will decompress it automatically, but if you are serving binary data that shouldn't be compressed (like images), you need to prevent compression.

Preventing Compression

Add this line immediately after setting your content type if you find your image is being served as a "broken icon" or with unexpected size changes:

header('Content-Type: image/png');
header('Content-Encoding: identity'); // Explicitly disable gzip compression

Alternatively, configure your web server (.htaccess or nginx.conf) to exclude the .png extension from compression rules. For Apache users, adding SetOutputFilter DEFLATE might compress everything unless you explicitly set AddType text/html .html and similar exclusions for images.

Final Verification

The fact that Internet Explorer behaves differently than modern browsers often stems from how IE handles partial content or specific header parsing quirks. While your PHP version (5.3.10) is quite old, the behavior regarding headers remains consistent across versions: the header must be sent before any byte leaves the output buffer.

If you are integrating this into a larger application where you cannot control the exact flow of execution, consider using a dedicated endpoint that only renders images. This isolates the logic and prevents accidental whitespace or template rendering from interfering with the image stream. By ensuring the Content-Type is set correctly and preventing compression, you ensure that the browser receives raw PNG bytes, eliminating the broken icon issue.

Our network