Roshan Shaw
Roshan Shaw

Reputation: 45

Downloading a file from server to client's computer

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?

Upvotes: 2

Views: 22298

Answers (2)

Chris Gregory
Chris Gregory

Reputation: 95

To continue on the original answer, I've added a few php functions to make it a bit more programmatic:

$filePath = $_GET['path'];
$fileName = basename($filePath);
if (empty($filePath)) {
    echo "'path' cannot be empty";
    exit;
}

if (!file_exists($filePath)) {
    echo "'$filePath' does not exist";
    exit;
}

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

If your sever requires strong security, do not use this function without pre-validating the user in the same script. Or use the security measures posted by the original answer. This script will allow any file on your server to be downloaded by a user.

Upvotes: 0

Waldz
Waldz

Reputation: 104

<?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>

Upvotes: 4

Related Questions