php文件限速下载示例代码

发布时间 2023-10-18 08:50:12作者: EternalChronosTime
<?php
// 将发送到客户端的本地文件
$local_file='abc.zip';
// 文件名
$download_file='your-download-name.zip';
// 设置下载速率(=> 31.2 kb/s)
$download_rate=31.2;
if(file_exists($local_file)&&is_file($local_file)){
 header('Cache-control: private');// 发送 headers
 header('Content-Type: application/octet-stream');
 header('Content-Length: '.filesize($local_file));
 header('Content-Disposition: filename='.$download_file);
 flush();// 刷新内容
 $file=fopen($local_file,"r");
 while (!feof($file)){
  print fread($file,round($download_rate*1024));// 发送当前部分文件给浏览者
  flush();// flush 内容输出到浏览器端
  sleep(1);// 终端1秒后继续
 }
 fclose($file);// 关闭文件流
}else{
 die('Error: 文件 '.$local_file.' 不存在!');
}

php文件限速下载示例代码

php教程 我的站长站 2022-05-07 共646人阅读  加入收藏

限速下载示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?php
// 将发送到客户端的本地文件
$local_file='abc.zip';
// 文件名
$download_file='your-download-name.zip';
// 设置下载速率(=> 31.2 kb/s)
$download_rate=31.2;
if(file_exists($local_file)&&is_file($local_file)){
 header('Cache-control: private');// 发送 headers
 header('Content-Type: application/octet-stream');
 header('Content-Length: '.filesize($local_file));
 header('Content-Disposition: filename='.$download_file);
 flush();// 刷新内容
 $file=fopen($local_file,"r");
 while (!feof($file)){
  print fread($file,round($download_rate*1024));// 发送当前部分文件给浏览者
  flush();// flush 内容输出到浏览器端
  sleep(1);// 终端1秒后继续
 }
 fclose($file);// 关闭文件流
}else{
 die('Error: 文件 '.$local_file.' 不存在!');
}

代码释义

代码中默认下载速度限制为31.2kb/s,即每秒仅向客户端发送20.5kb的文件流,直到发送完整个文件为止。

使用前需要添加头文件,声明Content-Type为application/octet-stream,表示该请求将以流的方式发送,并且声明Content-Length,即声明了文件流的大小。

在代码里使用了flush(),flush函数作用是刷新php程序的缓冲,实现print动态输出。

<?php
// 将发送到客户端的本地文件
$local_file='abc.zip';
// 文件名
$download_file='your-download-name.zip';
// 设置下载速率(=> 31.2 kb/s)
$download_rate=31.2;
if(file_exists($local_file)&&is_file($local_file)){
 header('Cache-control: private');// 发送 headers
 header('Content-Type: application/octet-stream');
 header('Content-Length: '.filesize($local_file));
 header('Content-Disposition: filename='.$download_file);
 flush();// 刷新内容
 $file=fopen($local_file,"r");
 while (!feof($file)){
  print fread($file,round($download_rate*1024));// 发送当前部分文件给浏览者
  flush();// flush 内容输出到浏览器端
  sleep(1);// 终端1秒后继续
 }
 fclose($file);// 关闭文件流
}else{
 die('Error: 文件 '.$local_file.' 不存在!');
}