PHP强制下载PDF的原理与实现
在处理文件传输时,常遇到PDF文档在浏览器中直接打开的情况,用户需手动执行另存为操作才能保存。为解决此问题,可利用PHP脚本强制触发文件的下载行为。
核心思路在于调整HTTP响应头部信息。具体做法是将Content-Type字段设定为application-x/force-download,从而指示浏览器以附件形式处理内容。
具体实现逻辑如下所示:
主要代码片段如下:
调用方式:forceDownload("pdfdemo.pdf");
定义函数 forceDownload($filename) {
首先验证文件是否存在,若 file_exists($filename) 返回 false,则
直接返回 false 终止执行。
}接下来配置HTTP头部信息:
设置 header('Content-Type: application-x/force-download');
设置 header('Content-Disposition: attachment; filename="' . basename($filename) .'"');
设置 header('Content-length: ' . filesize($filename));
针对旧版IE6浏览器进行兼容处理:
判断 if (false === strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6')) {
添加 header('Cache-Control: no-cache, must-revalidate');
}添加 header('Pragma: no-cache');
最后读取文件内容并输出:
执行 return readfile($filename);;
}为简化操作流程,封装了 forceDownload() 函数,开发者只需传入文件名即可实现强制下载功能。