php文件下载服务器代码

事情的起因

额,平板想下载电脑上的pdf文件,我开启了web服务,局域网下的ipad访问该文件web路径会直接打开该pdf,而不是下载。于是本小白就折腾了一下。

源代码
<?php
forceDownload("python.pdf");
function forceDownload($filename) {
set_time_limit(0);
if (false == file_exists($filename)) {
return false;
}
// http headers
header('Content-Type: application-x/force-download');
header('Content-Disposition: attachment; filename="' . basename($filename) .'"');
header('Content-length: ' . filesize($filename));
// for IE6
if (false === strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6')) {
header('Cache-Control: no-cache, must-revalidate');
}
// 打开文件
$fp = fopen($filename, 'rb');
// 设置指针位置
fseek($fp, 0);
// 开启缓冲区
ob_start();
// 分段读取文件
while (!feof($fp)) {
$chunk_size = 1024 * 1024 * 2; // 2MB
echo fread($fp, $chunk_size);
ob_flush(); // 刷新PHP缓冲区到Web服务器
flush(); // 刷新Web服务器缓冲区到浏览器
sleep(1); // 每1秒 下载 2 MB
}
// 关闭缓冲区
ob_end_clean();
fclose($fp);
}
?>
总结

注意下文件头 header('Content-Type: application-x/force-download');
还有分段读取文件的操作就好了。因为fread读取太大的文件会缓冲区溢出

参考链接1: http://www.zzvips.com/article/72915.html
参考链接2: https://www.cnblogs.com/bjzhangshihao/p/13281003.html

posted @ 2020-12-04 11:37  Throokie  阅读(338)  评论(0编辑  收藏  举报