php实现文件下载---header

本文介绍了一个使用PHP实现的文件下载脚本,该脚本能够检查文件是否存在,并通过设置HTTP头来正确地触发文件下载过程。此外,还展示了如何逐块读取并输出文件内容以确保大文件也能被顺利下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1 <?php
2
3 $file_name="123.txt";
4
5 $file_dir="";
6
7
8
9 $file_dir=chop($file_dir);
10
11 if($file_dir!='')
12
13 {
14
15 $file_path=$file_dir;
16
17 if(substr($file_dir,strlen($file_dir)-1,strlen($file_dir))!='/')
18
19 {
20
21 $filepath.='/';
22
23 }
24
25 $file_path.=$file_name;
26
27 }
28
29 else
30
31 {
32
33 $file_path=$file_name;
34
35 }
36
37
38
39 if(!file_exists($file_path))
40
41 {
42
43 die("<p><b>file doesn't exists</b></p>");
44
45 }
46
47 $file_size=filesize($file_path);
48
49 $fp=fopen($file_path,"r");
50
51 //begin writing headers
52
53 header("Cache-Control:must-revalidate");
54
55 header("Cache-Control:public");
56
57
58
59 header("Content-type:application/octet-stream");
60
61 header("Content-Range:bytes");
62
63 header("Content-Length:$file_size");
64
65 header("Content-Disposition:attachment;filename=".$file_name);
66
67 $buffer_size=10240;
68
69 while(!feof($fp))
70
71 {
72
73 $buffer=fread($fp,$buffer_size);
74
75 echo $buffer;
76
77 flush();
78
79 ob_flush();
80
81 }
82
83 fclose($fp);
84
85 exit;
86
87 ?>


 

转载于:https://www.cnblogs.com/RockFive/archive/2011/11/21/2257172.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值