Trigger to Download a File When Clicking Link

Demo Download

There are two ways to trigger to download a file.

  1. HTML 5 Download Attribute.
  2. Download File Using PHP Script.

The download attribute triggers a force download but it does not supported by Safari. Following are the versions that support download attribute.

Chrome = 14.0
Internet Explorer = 13.0
Firefox = 20.0
Opera = 15.0

Download File Using Using HTML 5 Download Attribute

<a href="SampleFile.pdf" download>Download File</a>

If you want to rename the file at the time of downloading, use the following code:

<a href="SampleFile.pdf" download="new_filename">Download File</a>

Download File Using PHP – Server Side Script

We will need to create PHP script file and pass the file name in the href attribute that we want to download as you can see below:

<a href="download.php?file=SampleFile.pdf" target="_new">Download File</a>

PHP Script

if (isset($_GET['file'])) {
$file = $_GET['file'];
if (file_exists($file) && is_readable($file) && preg_match('/\.pdf$/',$file)) {
	header('Content-Type: application/pdf');
	header("Content-Disposition: attachment; filename=\"$file\"");

The above file will read the file name and trigger to force download. This example will work on all browsers.

Note: I used this example for PDF file type, you can change it as per your requirement.

If you found this tutorial helpful so share it with your friends, developer groups and leave your comment.

Facebook Official Page: All PHP Tricks

Twitter Official Page: All PHP Tricks

Article By
Javed Ur Rehman is a passionate blogger and web developer, he loves to share web development tutorials and blogging tips. He usually writes about HTML, CSS, JavaScript, Jquery, Ajax, PHP and MySQL.
  1. Hi! Your example works in my modded download form. But I have a question, I tried it by passing the file name in my form action:

    Which works, but I need to hide the filename within the PHP, so I tried this:

    if (isset($_GET[‘file’])) {
    $file = $_GET[‘file.rar’];
    if (file_exists($file) && is_readable($file) && preg_match(‘/\.rar$/’,$file)) {
    header(‘Content-Type: application/rar-compressed’);
    header(“Content-Disposition: attachment; filename=\”$file\””);

    But it doesn’t work. It just refreshes the page when you click the download button and nothing downloads. Can you assist? Thanks!

  2. Very nice. i implemented same things using same trick trough ajax but its not working, with PHP working when i run direct to file can you suggest me how can i implement with ajax.

  3. thank javed. you know I want to make a music website and I ask will this help or is there any suggestion based on that

Leave a Reply

Your email address will not be published. Required fields are marked *