Serving a file download using PHP
First PHP project and I'm stuck!
I wish to allow users to click a bu开发者_如何学JAVAtton or a link and download a file.However, my PHP must first perform some tasks, choose the right file, record the download event in a db etc. This I can do, but how do I then send the file as a response to the user's click?
Thanks for any help.
As @Sarfraz suggests, you can, after doing the tasks you need to do, send a Content-Type
header to the browser and then spew out the contents of the file to the browser. The browser will then perform according to user settings, which in general will be either a) open and display the file or b) save the file to disk.
If you want to force the file to be saved to disk instead of displayed in the browser, a commonly used method is to specify a mime-type of Content-Type: application/octet-stream
. It is possible to specify an attachment filename as well, with the header Content-Disposition: attachment; filename=foobar.baz
.
Send the appropriate header in your script:
header("content-type: application/pdf");
Use the correct mime-type
as per your file and send the content to the browser using readfile
.
header("Content-type: image/png");
(or whatever it is), and then you just output the file.
Here is a function that can be used to send files directly to the browser.
$fileName
: the path+name of the file that needs to be sent to the browser
$downloadName
: this is the name (no path needed) of the file that the user sees in it's download (is not necessarly the same as $filename
function sendFileDirectlyToBrowser($downloadName, $fileName) {
if (! file_exists($fileName)) {
throw new Exception('file does not exist!');
}
$pathInfo = pathinfo($fileName);
//list with mime-types http://en.wikipedia.org/wiki/Mime_type#List_of_common_media_types
switch (strtolower($pathInfo['extension'])) {
case 'csv':
header("Content-type: test/csv");
break;
case 'doc':
case 'docx':
header("Content-type: application/msword");
break;
case 'gif':
header("Content-type: image/gif");
break;
case 'jpg':
case 'jpeg':
header("Content-type: image/jpeg");
break;
case 'png':
header("Content-type: image/png");
break;
case 'pdf':
header("Content-type: application/pdf");
break;
case 'tiff':
header("Content-type: image/tiff");
break;
case 'txt':
header("Content-type: text/plain");
break;
case 'zip':
header("Content-type: application/zip");
break;
case 'xls':
case 'xlsx':
if(!(strpos($HTTP_USER_AGENT,'MSIE') === false)) {
header("Content-type:application/x-msdownload");
}
else {
header("Content-type:application/vnd.ms-excel ");
}
break;
}
header('Content-Disposition:attachment;filename="' . $downloadName . '"');
print file_get_contents($fileName);
}
精彩评论