Downloading a file from server to client's computer

18,493
<?php
/**
 * download.php
 */

if (!empty($_GET['file'])) {
    // Security, down allow to pass ANY PATH in your server
    $fileName = basename($_GET['file']);
} else {
    return;
}

$filePath = '???/files/' . $fileName;
if (!file_exists($filePath)) {
    return;
}

header("Content-disposition: attachment; filename=" . $fileName);
header("Content-type: application/pdf");
readfile($filePath);

And actually AJAX request is unnecessary, when using Content-disposition: attachment:

<a href="download.php?file=file1.pdf">File1</a>
Share:
18,493
Roshan Shaw
Author by

Roshan Shaw

Updated on June 04, 2022

Comments

  • Roshan Shaw
    Roshan Shaw almost 2 years

    I have a folder in my root dir called files. This folder contains files ranging from 1 Kb-1 GB.

    I want a php script that can simply download a file asynchronously using AJAX.

    This codes initiates download scripts when a file is clicked:

    JQUERY

    $('.download').click(function(){
       var src =$(this).attr('src');  
       $.post('download.php',{
          src :  src //contains name of file 
        },function(data){
          alert('Downloaded!');
        });
    });
    

    PHP

    <?php
       $path = 'files/'.$_POST['src'];
       //here the download script must go!
    ?>
    

    Which would be the best, fastest and secure way to download a file?

  • Roshan Shaw
    Roshan Shaw over 9 years
    what if i dont know the content-type ?
  • Waldz
    Waldz over 9 years
    Just dont use it when. It helps browser to determine program for file opening (movie, image, MS word etc.)
  • Quentin
    Quentin over 9 years
    You can't not use a Content-Type. PHP will default to claiming it is an HTML document unless you override that.
  • Saumil
    Saumil almost 9 years
    Upvote.... Don't want to be a nit-picker but you have a typo for 'file_exits'. It should be 'file_exists'. Some people might not know how to correct this error, so please correct it.