Forcing to download a file using PHP

Forcing to download a file using PHP

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

Stefan Bogdanescu

Founder & Senior Architect

Forcing to download a file using PHP

When a user clicks a link to what should be a file download, but instead the browser attempts to render it in a new tab or window, the issue usually lies in how the server identifies the content type and how the browser interprets that identifier. In your specific case, linking directly to example.csv causes the web server to serve the raw bytes of the file with a MIME type like text/csv. Modern browsers are quite intelligent; upon seeing this header, they often assume the user wants to inspect the data immediately rather than saving it, so they open an empty tab and attempt to display the grid.

To force a download, you need to explicitly tell the browser that this resource is not meant for immediate display but should be treated as binary data attached to the request. This is where csv.php comes into play. By serving PHP code that sets specific HTTP headers before echoing any content, you can override the default behavior of the web server.

Your initial attempt using header('Content-Type: application/csv') and Content-Disposition: attachment; filename=example.csv is on the right track. The Content-Disposition header is critical here. When set to inline, browsers display the content. When set to attachment, they prompt a save dialog. However, the problem you encountered—where a new file is created instead of downloading the original CSV—suggests that the output buffer might be empty or that the headers are being sent without any body content following them.

In PHP, if you send headers and then immediately stop execution without outputting data, the browser receives a 204 No Content response (or similar) with no body to download. If the file is genuinely missing from the path or if the script terminates early, the server might behave unexpectedly depending on configuration. To fix this, your csv.php script must read the physical file and echo its contents back to the client.

Here is a robust implementation pattern for csv.php:

<?php
$filename = 'files/csv/example/example.csv';

// Ensure the file exists before proceeding
if (!file_exists($filename)) {
    http_response_code(404);
    exit('File not found');
}

// Force download headers
header('Content-Type: application/vnd.ms-excel'); // Often safer than application/csv for legacy clients
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
header('Pragma: no-cache');
header('Expires: 0');

// Read the file and output it
echo readfile($filename);
exit();

There are a few nuances to consider in this approach. First, the Content-Type. While application/csv is technically correct for CSV data, many older clients or specific browser configurations prefer text/csv or even treat it as a generic octet stream if no standard type exists. Some developers use application/vnd.ms-excel simply because it forces Excel-compatible behavior across all browsers, but this can cause issues if the CSV contains special characters that Excel interprets strangely.

Secondly, you must ensure that no whitespace or output is sent before the headers. If your file path includes a directory structure like files/csv/example/, make sure the web server has read permissions for that specific directory. If the path is incorrect, PHP might throw a fatal error, which would break the download entirely.

If you are working within a Laravel application, handling this logic directly in a raw controller method works fine, but it can be cleaner to use Laravel's response facade. The facade allows you to send headers and return the file content in one go:

use Illuminate\Support\Facades\Response;
use Illuminate\Http\Request;

return Response::download(
    'files/csv/example/example.csv',
    'example.csv'
);

This approach is generally preferred in modern frameworks because it handles encoding, security checks, and header manipulation internally. It ensures that the original filename is preserved in the download while allowing you to customize the displayed name if necessary.

The primary trade-off with the manual PHP method is the lack of automatic handling for edge cases like file locking or concurrent downloads. If multiple users try to download the same file simultaneously via the readfile approach without proper locking, there is a small risk of data inconsistency in rare scenarios involving large files being modified while serving them.

In summary, ensuring the file path is correct, verifying that headers are sent before any output, and explicitly echoing the file content resolves the "new file created" issue. Whether you use raw PHP or a framework helper like Laravel's Response::download, the goal remains the same: bridge the gap between the static asset on disk and the browser's expectation of a downloadable attachment.

Our network