限速下载示例代码
- <?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动态输出。
这样子论坛 博客这些就不必担心突然间暴增下载 拖死服务器了。
|