您正在寻找的可能是一种强制下载任何文件类型的方法吗?
看看这段代码,你可能想要添加更多的 mime 类型,具体取决于你让人们下载的文件类型。
此代码复制自:http ://davidwalsh.name/php-force-download
// http://davidwalsh.name/php-force-download
// grab the requested file's name
$file_name = $_GET['file'];
// make sure it's a file before doing anything!
if(is_file($file_name)) {
/*
Do any processing you'd like here:
1. Increment a counter
2. Do something with the DB
3. Check user permissions
4. Anything you want!
*/
// required for IE
if(ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); }
// get the file mime type using the file extension
switch(strtolower(substr(strrchr($file_name, '.'), 1))) {
case 'pdf': $mime = 'application/pdf'; break;
case 'zip': $mime = 'application/zip'; break;
case 'jpeg':
case 'jpg': $mime = 'image/jpg'; break;
default: $mime = 'application/force-download';
}
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ($file_name)).' GMT');
header('Cache-Control: private',false);
header('Content-Type: '.$mime);
header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($file_name)); // provide file size
header('Connection: close');
readfile($file_name); // push it out
exit();
}
当他们单击下载链接时,您只需要创建一个新的 php 页面(或相同的页面),它会转到带有文件名参数“file = {filename}”的新页面(或相同的页面)。为了安全起见,不要包含文件路径。这种方法存在安全问题,但对您来说可能无关紧要,这完全取决于您的情况以及正在下载的内容以及它是否是公共数据?