找回密码
 立即注册

网站怎么限制用户下载附件速度?教程来了!!

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

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

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

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


这样子论坛 博客这些就不必担心突然间暴增下载 拖死服务器了。



全部评论 0

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

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

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

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


这样子论坛 博客这些就不必担心突然间暴增下载 拖死服务器了。



热门推荐
您需要登录后才可以回帖 立即登录
说说你的想法......
0
0
0
返回顶部