Send file to the user

Send file to the user

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

Stefan Bogdanescu

Founder & Senior Architect

Streaming Files Without Overloading Memory

When a user triggers a request to deliver a PDF from disk, the immediate instinct might be to load the entire file into memory and echo it back. While this approach works for small documents, it creates a significant bottleneck as soon as file sizes grow beyond a few megabytes. Reading a 50MB PDF entirely into RAM before sending it to the browser can cause high memory usage or even trigger an OutOfMemory exception in PHP, especially on shared hosting environments with strict limits.

The robust solution is to stream the file directly from the disk to the output buffer. This method keeps memory footprint low by processing the file byte-by-byte rather than loading the whole content at once. In a typical scenario, you verify that the request method is GET, check if the file exists, and then open a file handle pointing to the path of the PDF.

You iterate over the file handle in chunks, writing each chunk directly to the output buffer using fread and echo. This ensures that data flows through the network pipe without clogging up PHP's internal memory allocator. Here is a conceptual example of how this looks in raw PHP:

if ($_SERVER['REQUEST_METHOD'] === 'GET' && file_exists($pdfPath)) {
    $handle = fopen($pdfPath, 'rb');
    
    if ($handle) {
        while (!feof($handle)) {
            echo fread($handle, 8192);
        }
        
        fclose($handle);
        exit;
    }
} else {
    http_response_code(404);
    echo 'File not found';
}

However, raw PHP scripts lack the ability to send proper headers for file downloads or force a browser cache policy. You must set the Content-Type header to application/pdf and include the Content-Length if you know the file size, which helps the browser display the correct progress bar during download. Setting these headers requires knowing the file size beforehand, which implies reading the file metadata (like using filesize()) before the streaming loop begins.

Laravel provides a cleaner abstraction for this exact scenario. If you are building an API or handling requests within a Laravel application, the Response facade handles the stream mechanics internally. You can create a response object by passing the path to your PDF file directly into response()->download(). This automatically sets the correct content type and headers, allowing the browser to handle the download seamlessly without you managing the file pointer manually.

use Illuminate\Support\Facades\Response;

if (file_exists($pdfPath)) {
    return Response::download($pdfPath);
}

There are specific trade-offs to consider when choosing between raw PHP and framework helpers. Using response()->download() is generally preferred in modern stacks because it handles edge cases like missing files gracefully by returning a 404 response automatically. However, in high-performance scenarios where you need to customize the stream behavior—such as compressing the data on the fly or adding dynamic query parameters to the filename—you might find yourself needing to implement the manual streaming logic anyway.

A common pitfall is forgetting to call exit after echoing the file content in a raw script. If control flow continues after the loop, you might accidentally append HTML or other output to the binary stream, corrupting the PDF and causing an "Invalid PDF" error when the user tries to open it. Always terminate the script immediately after sending the file contents.

For large-scale applications, consider whether the file needs to be downloaded or if a preview is sufficient. If you are serving PDFs via an API endpoint, ensure your CORS configuration allows cross-origin requests, as browsers will block these by default if headers aren't set correctly. By understanding these nuances, you ensure reliable file delivery that scales with your application's growth.

Our network