php实现文件下载限速

PHP 实现文件下载限速:

读取文件:

1
2
3
4
5
6
7
8
9
10
$file = './a.mp4';

$file_name = '测试.mp4';

// 打开文件具柄
$handle = fopen($file, 'rb');

if ($handle == false) {
die('read file fail');
}

设置文件下载响应头

1
2
3
4
5
6
7
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachement; filename=xxx.mp4');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));

方案一

1
2
3
4
5
6
7
8
9
10
while (!feof($handle)) {
$data = fread($handle, 1024);

if ($data == false) {
fclose($handle);
return true;
}
usleep(5000);
echo $data;
}

方案二

1
2
3
4
5
6
7
8
$count = ceil($size / $limit);
while ($count > 0) {
$data = fread($handle, $limit);
$count--;
echo $data;
ob_flush();
sleep(1);
}

完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php

$file = './a.mp4';

$file_name = '测试.mp4';

// 打开文件具柄
$handle = fopen($file, 'rb');

if ($handle == false) {
die('read file fail');
}

// 设置文件下载响应头

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachement; filename=另你讲师集锦.mp4');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));

$size = filesize($file); //文件大小
$limit = 1024*1024; // 每次读取文件的大小
#### 方案一
// while (!feof($handle)) {
// $data = fread($handle, 1024);

// if ($data == false) {
// fclose($handle);
// return true;
// }
// usleep(5000);
// echo $data;
// }

#### 方案二
$count = ceil($size / $limit);
while ($count > 0) {
$data = fread($handle, $limit);
$count--;
echo $data;
ob_flush();
sleep(1);
}
坚持原创技术分享,您的支持将鼓励我继续创作!
//