Output an Image in PHP

Output an Image in PHP

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

Stefan Bogdanescu

Founder & Senior Architect

Outputting Images in PHP: Direct Streams and Security Considerations

When you need to serve an image file stored on your filesystem to a browser, the most straightforward approach is using readfile(). This function reads the entire contents of a file from disk and writes it directly to the standard output stream. If the script's output buffer is empty and no headers have been sent previously, the server sends the raw bytes immediately.

To ensure the browser renders the image correctly rather than downloading it as a generic file, you must send the appropriate HTTP response headers before calling readfile(). Specifically, you need to set the Content-Type header to match the MIME type of the image. In your scenario, where the MIME type is already available in a variable $type, the implementation looks like this:

$file = '../image.jpg';
$type = 'image/jpeg';

// Send headers first
header("Content-Type: $type");

// Output the file content
readfile($file);

This pattern relies on the principle that readfile() returns the number of bytes read, but its primary side effect is writing to STDOUT. By ensuring no previous output (like whitespace or error messages) exists before the header call, you prevent HTTP 500 errors related to "headers already sent."

Handling Unknown File Extensions

A common pitfall in image serving logic is assuming that the file extension dictates the MIME type. While image.jpg implies JPEG, relying on .jpg, .jpeg, or .png extensions alone can lead to security vulnerabilities if a malicious actor renames a non-image file to .gif. The source material specifies that the MIME type is determined by $type, which suggests you are already decoupling the content type from the filename.

However, this separation requires careful implementation of validation logic. If $type comes from user input or database records, never trust it blindly. Instead, validate against a whitelist of known image types before sending headers:

$allowedMimes = [
    'image/jpeg' => ['jpg', 'jpeg'],
    'image/png'  => ['png'],
    'image/gif'  => ['gif'],
];

$fileExtension = pathinfo($file, PATHINFO_EXTENSION);
$allowedExtensions = $allowedMimes[$type] ?? null;

if ($allowedExtensions && in_array(strtolower($fileExtension), $allowedExtensions)) {
    header("Content-Type: $type");
    readfile($file);
} else {
    http_response_code(403);
    echo 'Forbidden';
}

This approach ensures that even if someone uploads a shell script named script.png, the server will reject it because the MIME type image/png does not match the allowed extensions for that content type.

Stream vs. Load: Memory Efficiency

For large images, readfile() is significantly more efficient than loading the entire file into memory using file_get_contents(). When you use file_get_contents($file), PHP allocates a string equal to the file size in RAM before echoing it. If the image is 50MB, you temporarily need roughly 100MB of RAM (accounting for overhead).

In contrast, readfile() reads chunks from the disk and writes them to the output stream without ever loading the whole file into memory simultaneously. This makes readfile() the preferred choice for serving large assets, as it minimizes peak memory usage and reduces the risk of triggering PHP's memory limits (memory_limit).

Integration with Laravel Ecosystem

If you are building an application using Laravel, the same principles apply, but the implementation often leverages framework helpers. You might find yourself storing images in the public/storage directory and needing to serve them dynamically. While Laravel provides the Storage facade for file manipulation, serving raw files directly still requires handling headers manually if you aren't using a route that automatically determines content types based on path extensions.

For dynamic image serving in a Laravel context, consider whether you need to process the image first. If $type indicates a specific format and you want to ensure consistency, you might convert the file before outputting it. However, simple delivery often just requires passing the raw bytes through readfile() with the correct header.

There are advanced scenarios where you might use LaravelCompany resources to manage complex asset pipelines or custom middleware that intercepts these requests, but for basic image output, sticking to standard PHP streams remains robust and performant.

Our network