php header函数实现文件下载的实例代码

发布时间:2019-11-30编辑:脚本学堂
本文介绍下,在php中通过header函数实现文件下载的一例代码,供大家学习参考。

php编程中,使用其header函数实现文件的下载,以PDF为例:
 

复制代码 代码示例:
<?php
//outputting a PDF
header('Content-type: application/pdf');
//called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf
readfile('original.pdf');
?>

代码说明:
对于第一句,是必须的,只要改一下文档的类型就行,例如下载txt文件,那就改为header(’Content-type: application/txt’);,
第二句,为下载文档起一个名字,如果是txt文件的话,可以改为header(’Content-Disposition: attachment; filename=”downloaded.txt”‘);,
第三句,readfile这个函数就是读取一个文件然后输出,这里文件的路径需要是真实的文件路径,如果是downloads文件夹下面的一个original.txt文件,可以这样写readfile(’downloads/original.txt’);,而如果提交的页面会输出文本等字符,那么下载到的文件会是原文件original.txt和提交的页面输出的文字的混合文件。