PHP实现限速下载文件示例
复制代码 代码如下: // 本地文件路径,需发送给客户端 $local_file = 'test-file.zip';
// 用户默认获取的文件名 $download_file = 'your-download-name.zip';
// set the download rate limit (=> 20,5 kb/s) $download_rate = 20.5;
if(file_exists($local_file) && is_file($local_file)) {
// 发送HTTP头部信息 header('Cache-control: private'); 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();
// 暂停一秒执行 sleep(1); }
// 关闭文件流 fclose($file);
}
else { die('Error: The file '.$local_file.' does not exist!'); }