2 回答

TA贡献1846条经验 获得超7个赞
<a href="downloader.php?file=filename.extension">filename</a>
然后在downloader.php文件中
<?php
ignore_user_abort(true); // prevents script termination
set_time_limit(0); // prevent time out
$file = isset($_GET['file']) ? $_GET['file'] : ''; //get filename
if ($file) {
$path_info = pathinfo($_GET['file']);
$file_name = $path_info['basename'];
$dir = "uploads"; //directory
$path_to_file = $dir.'/'.$file_name; //full path
if(!file_exists($path_to_file)) { // check if file exist or terminate request
exit('the file does not exist');
}
if(!is_readable($path_to_file)) { //check if file is readable from the directory
exit("security issues. can't read file from folder");
}
// set download headers for file
$finfo = finfo_open(FILEINFO_MIME_TYPE);
header('Content-Type: ' . finfo_file($finfo, $path_to_file));
$finfo = finfo_open(FILEINFO_MIME_ENCODING);
header('Content-Transfer-Encoding: ' . finfo_file($finfo, $path_to_file));
`header('Content-disposition: attachment; filename="' .` basename($path_to_file) . '"');
readfile($path_to_file); // force download file with readfile()
} else {
exit('download paramater missing');
}
?>

TA贡献1829条经验 获得超7个赞
首先创建一个将接受参数的下载处理程序文件。
我将其命名为 download.php
下载.php
<?php
ignore_user_abort(true); // prevents script termination
set_time_limit(0); // prevent time out
$file = isset($_GET['file']) ? $_GET['file'] : ''; //get filename
if ($file) {
$path_info = pathinfo($_GET['file']);
$file_name = $path_info['basename'];
$dir = "uploads"; //directory
$path_to_file = $dir.'/'.$file_name; //full path
if(!file_exists($path_to_file)) { // check if file exist or terminate request
exit('the file does not exist');
}
if(!is_readable($path_to_file)) { //check if file is readable from the directory
exit("security issues. can't read file from folder");
}
// set download headers for file
$finfo = finfo_open(FILEINFO_MIME_TYPE);
header('Content-Type: ' . finfo_file($finfo, $path_to_file));
$finfo = finfo_open(FILEINFO_MIME_ENCODING);
header('Content-Transfer-Encoding: ' . finfo_file($finfo, $path_to_file));
header('Content-disposition: attachment; filename="' . basename($path_to_file) . '"');
readfile($path_to_file); // force download file with readfile()
}
else {
exit('download paramater missing');
}
?>
用法
<a href="download.php?file=randomfilename.pdf">My pdf </a>
希望这可以帮助。
- 2 回答
- 0 关注
- 153 浏览
添加回答
举报