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>
Author by
Roshan Shaw
Updated on June 04, 2022Comments
-
Roshan Shaw almost 2 years
I have a folder in my root dir called
files
. This folder contains files ranging from1 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 over 9 yearswhat if i dont know the
content-type
? -
Waldz over 9 yearsJust dont use it when. It helps browser to determine program for file opening (movie, image, MS word etc.)
-
Quentin over 9 yearsYou can't not use a Content-Type. PHP will default to claiming it is an HTML document unless you override that.
-
Saumil almost 9 yearsUpvote.... 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.