简体   繁体   English

限制PHP的下载速度

[英]Throttling download speed in PHP

I have tried the basic ones found in a Google search and even tried to write one myself, however i keep getting a problem with it. 我已经尝试过在Google搜索中找到的基本搜索,甚至尝试自己写一个,但是我一直遇到问题。 It seems to download the content server-side or something and then push it to the user, which will already have been downloaded. 似乎是在服务器端或其他地方下载内容,然后将其推送给已经下载的用户。 It will open the download page and take around 10 seconds to download and then give the file to the user in full, which makes it look like its not downloading. 它将打开下载页面,大约需要10秒钟来下载文件,然后将文件完全提供给用户,这使其看起来好像没有下载。

I was wondering if there are any classes that have been written to throttle download speeds, or how i can fix this problem. 我想知道是否已编写任何类来限制下载速度,或者如何解决此问题。

I have this currently; 我现在有这个

header("Content-type: application/force-download");
    header("Content-Transfer-Encoding: Binary");
    header("Content-length: ".filesize("uploads/$filename"));
    header("Content-disposition: attachment; filename=\"$origname");
    readfile("uploads/$filename");

Thanks! 谢谢!

@set_time_limit(0); // don't abort if it takes to long
header("Content-type: application/force-download");
header("Content-Transfer-Encoding: Binary");
header("Content-length: ".filesize("uploads/".$filename));
header('Content-disposition: attachment; filename="'.$origname.'"');
$perSecond = 5; // 5 bytes per second

$file = fopen("uploads/".$filename, 'r');
while(!feof($file)) {
    echo fread($file, $perSecond);
    flush();
    sleep(1);
}

This will send a file with throttled download speed to the user. 这会将下载速度受到限制的文件发送给用户。 It works basically like this: 它的工作原理基本上是这样的:

  • Open a file 开启档案
  • loop until we are at the end 循环直到我们结束
  • echo X bytes 回显X字节
  • flush the output to the User 将输出刷新给用户
  • sleep for one second. 睡一秒钟。

I was wondering if there are any classes that have been written to throttle download speeds 我想知道是否编写了任何类来限制下载速度

Now there is: bandwidth-throttle/bandwidth-throttle 现在有: bandwidth-throttle/bandwidth-throttle

use bandwidthThrottle\BandwidthThrottle;

$in  = fopen(__DIR__ . "/resources/video.mpg", "r");
$out = fopen("php://output", "w");

$throttle = new BandwidthThrottle();
$throttle->setRate(100, BandwidthThrottle::KIBIBYTES); // Set limit to 100KiB/s
$throttle->throttle($out);

stream_copy_to_stream($in, $out);

You might find my alpha-stage Bandwidth project of interest. 您可能会发现我感兴趣的alpha阶段带宽项目。 Probably needs a bit more work, but there's plenty of interesting stuff already. 可能需要更多的工作,但是已经有很多有趣的东西。 I don't think it has a F/OSS license yet; 我认为它还没有F / OSS许可证。 ping me if you want me to give it one! 如果您要我给它一个ping我!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM