一直很好奇限速下载是怎么做到的,网上查了下资料,发现其实很简单。
我们先来看看一般是怎么下载的
<?php$file = 'tt.zip';if (file_exists($file)){//获取文件后缀$suffix = pathinfo($file, PATHINFO_EXTENSION);//设置下载的header头header("Content-type: application/octet-stream");//告诉浏览器这是文件流格式文件header("Accept-Ranges: bytes");//告诉浏览器单位是字节header("Content-Length: " . filesize($file));//告诉浏览器文件大小header("Content-Disposition: attachment; filename=" . md5(time()).'.'.$suffix );//下载文件名echo file_get_contents($file);}
如果文件不大的话,那么是可以这样的。如果文件很大的话,这样的方式会使内存瞬间用完的,导致溢出。那么我们可以分段读取,并且分段输出。那么想做限速的话,就可以在这上面做文章了,我们看看下面的代码
<?php
$file = 'tt.zip';
if (file_exists($file)){
//获取文件后缀
$suffix = pathinfo($file, PATHINFO_EXTENSION);
//设置下载的header头
header("Content-type: application/octet-stream");//告诉浏览器这是文件流格式文件
header("Accept-Ranges: bytes");//告诉浏览器单位是字节
header("Content-Length: " . filesize($file));//告诉浏览器文件大小
header("Content-Disposition: attachment; filename=" . md5(time()).'.'.$suffix );//下载文件名
//打开文件
$file_resource = fopen($file,"r");
//循环读取文件,一次性读取102400字节,也就是100kb
while (!feof($file_resource)){
echo fread($file_resource,102400);//一次读取100kb并发送
sleep(1);
}
fclose($file_resource);// 关闭文件流
}
一次只读100kb的数据输出,中间再间隔一段时间,这样是不是就是限速了呢?去试试吧
