Home  >  Article  >  php教程  >  php实现限制文件下载速度的代码实例

php实现限制文件下载速度的代码实例

WBOY
WBOYOriginal
2016-06-07 11:42:181096browse

有时候你会出于某种目的而要求把下载文件的速度放慢一些,例如你想实现文件下载进度条功能。限制下载速度最大的好处是节省带宽,避免瞬时流量过大而造成网络堵塞。
// 将发送到客户端的本地文件<br> $local_file = 'test-file.zip';<br> // 文件名<br> $download_file = 'your-download-name.zip';<br> // 设置下载速率(=> 20,5 kb/s)<br> $download_rate = 20.5;<br> if(file_exists($local_file) && is_file($local_file)) {<br>     // 发送 headers<br>     header('Cache-control: private');<br>     header('Content-Type: application/octet-stream');<br>     header('Content-Length: '.filesize($local_file));<br>     header('Content-Disposition: filename='.$download_file);<br>     // flush 内容<br>     flush();<br>     // 打开文件流<br>     $file = fopen($local_file, "r");<br>     while (!feof($file)) {<br>         // 发送当前部分文件给浏览者<br>         print fread($file, round($download_rate * 1024));<br>         // flush 内容输出到浏览器端<br>         flush();<br>         ob_flush();  //防止PHP或web服务器的缓存机制影响输出<br>         // 终端1秒后继续<br>         sleep(1);<br>     }<br>     // 关闭文件流<br>     fclose($file);<br> }<br> else {<br>     die('Error: 文件 '.$local_file.' 不存在!');<br> }分析:上述实例把文件下载速度限制为20.5kb/s,即每秒仅向客户端发送20.5kb的文件流,直到发送完整个文件为止。如果没有该限制,那么文件将以流的形式一起发送到客户端,有多少发送多少,这会出现什么情况?假如文件大小为2m,那么一下子把2m的数据流传送过去,这将可能导致网络堵塞而中断脚本的执行,这种下载方式是不能在实际应用中采用的。

技术方面,首先添加头文件,声明Content-Type为application/octet-stream,表示该请求将以流的方式发送,并且声明Content-Length,即声明了文件流的大小。在代码里使用了flush(),flush函数作用是刷新php程序的缓冲,实现print 动态输出。

上述代码,经过巧妙使用,可以实现客户端显示文件下载进度条的功能,有兴趣的话不妨试试。

AD:真正免费,域名+虚机+企业邮箱=0元

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn