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 關注
- 168 瀏覽
添加回答
舉報