Forcing file download Edit on GitHub In category: PHP

Using PHP #php

The most reliable way to force file download is to set proper headers using a server-side technology such as PHP. Theoretically, browser can just ignore the headers but it's unlikely to happen.

$filename = 'test.txt';

header('Content-Type: text/plain'); // Set file MIME type here
header('Content-Disposition: attachment; filename="' . basename($filename) . '";');
header('Content-Length:' . filesize($filename));



Don't use application/force-download as Content-Type. It's an ugly hack, not a valid MIME type and it may cause unexpected behaviour.

Using HTML(Applicable in versions: HTML 5) #html

Some modern browsers also support download attribute specified in HTML 5.

<a href="test.txt" download>Download me!</a>

<!-- XHTML 5 compliant version -->
<a href="test.txt" download="download">Download me!</a>

Learn more #learn-more

Comments #comments