How to Automatically Start a Download in PHP?

How to Automatically Start a Download in PHP?

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

Stefan Bogdanescu

Founder & Senior Architect

How to Automatically Start a Download in PHP

To force a browser to download a file rather than displaying it inline, you must manipulate the HTTP response headers before sending any body content. The most critical header is Content-Disposition, which tells the user agent how to handle the payload. Setting this header to attachment instructs the browser to treat the response as downloadable data, prompting the "Save As" dialog or initiating the download immediately depending on the client's configuration.

You also need to set the Content-Type header correctly. Browsers use this value to determine how to render content. For a file, you typically want to serve it with its specific MIME type, such as application/pdf for documents or application/octet-stream for generic binary data. If you omit the Content-Disposition header entirely, modern browsers will often attempt to render the content in a new tab or window.

Here is a minimal PHP implementation that triggers an immediate download:

<?php
// Define the path to your file
$file = '/path/to/your/file.pdf';
$filename = basename($file);

// Ensure the file exists before attempting to send headers
if (file_exists($file)) {
    // Set the content type based on the file extension or specific MIME type
    $mimeType = 'application/pdf'; 
    
    // Force download by setting Content-Disposition to attachment
    header('Content-Type: ' . $mimeType);
    header('Content-Disposition: attachment; filename="' . $filename . '"');

    // It is often good practice to set the Content-Length if you know it
    // This allows some browsers to show progress bars accurately.
    header('Content-Length: ' . filesize($file));

    // Flush output buffers immediately to ensure headers are sent before body
    if (ob_get_length()) {
        ob_end_clean();
    }

    // Read and send the file contents
    readfile($file);
} else {
    http_response_code(404);
    echo 'File not found.';
}
?>

The logic here relies on readfile(), which reads the entire file from disk and outputs it directly to the browser. This is generally more efficient than reading the file into memory with fopen() and stream_copy_to_stream() unless you are dealing with streaming scenarios or massive files where you need to process chunks.

One common pitfall involves output buffering. If any whitespace—like a blank line or a BOM—exists between the opening PHP tag and the first header() call, PHP will emit an HTTP header error stating "Cannot modify header information." This happens because headers must be sent before any body content. The code snippet above includes ob_end_clean() to handle cases where output buffering might have already started, ensuring headers are flushed cleanly.

Another consideration is URL encoding in the filename. While modern browsers handle UTF-8 filenames reasonably well, passing special characters like spaces or ampersands directly can cause issues depending on the browser's interpretation of the header value. It is safer to URL-encode the filename using rawurlencode() if you expect non-standard characters, though basename() usually suffices for standard alphanumeric paths.

In a larger application framework like Laravel, you might not want to write raw headers manually every time. You can use the helper methods provided by the framework to handle this cleanly. For example, you could define a controller action that returns a file response:

use Illuminate\Http\Response;

public function downloadFile()
{
    $file = storage_path('files/report.pdf');
    
    return Response::download($file, 'Report_2023.pdf', [
        'Content-Type' => 'application/pdf',
    ]);
}

Laravel's Response::download() method automatically sets the necessary headers and handles the file streaming internally. However, be aware that if you are using this inside a route closure where you have already echoed something or included assets before the response is generated, you will encounter header modification errors. Always ensure no output has been sent prior to invoking these helper methods.

Security is also paramount when serving files directly. Never trust user input for the file path without strict validation. An attacker could attempt to access sensitive system files if the path is not sanitized. Additionally, ensure that the downloaded file hasn't been modified by malware between the time it was uploaded and the time it is served. If you are handling user-uploaded files, consider storing them outside the web root or using a dedicated service like AWS S3 with signed URLs to serve them securely.

Our network