当前位置: 移动技术网 > IT编程>开发语言>PHP > 使用PHP强制下载PDF文件示例

使用PHP强制下载PDF文件示例

2019年03月31日  | 移动技术网IT编程  | 我要评论
我们有时会遇到这样一种情况,当需要下载一个pdf文件时,如果不经处理会直接在浏览器里打开pdf文件,然后再需要通过另存为才能保存下载文件。本文将通过php来实现直接下载pdf文件。

实现原理:我们仅仅只需要修改页面http头,把content-type设置为force-download,问题即可解决。

请看代码:
复制代码 代码如下:

forcedownload("pdfdemo.pdf");
function forcedownload($filename) {

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');
}
header('pragma: no-cache');

// read file content and output
return readfile($filename);;
}

为了方便,我写了一个函数forcedownload(),然后通过调用该函数即可。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网