【问题标题】:Throttling download speed in PHP在 PHP 中限制下载速度
【发布时间】:2012-02-05 20:24:59
【问题描述】:

我已经尝试了在谷歌搜索中找到的基本的,甚至尝试自己写一个,但是我一直遇到问题。似乎是在服务器端下载内容或其他东西,然后将其推送给用户,该用户已经下载了。它会打开下载页面,大约需要 10 秒的时间来下载,然后将文件完整地提供给用户,这看起来像是没有下载。

我想知道是否已经编写了任何类来限制下载速度,或者我该如何解决这个问题。

我现在有这个;

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");

谢谢!

【问题讨论】:

标签: php download bandwidth


【解决方案1】:
@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);
}

这将向用户发送一个下载速度受限制的文件。它的工作原理基本上是这样的:

  • 打开文件
  • 循环直到结束
  • 回显 X 个字节
  • 将输出刷新到用户
  • 睡一秒钟。

【讨论】:

  • 我已经添加了它目前的样子,我将如何整合它?
  • @HarryBeasant 只需将 readfile 替换为我的 sn-p 和 file.txt 在我的 sn-p 中用您的文件名(当然还有 perSecond) 编辑:我刚刚更新了我的答案
  • 完成了,问题是它处理下载服务器端,然后将其推送到浏览器。所以你看不到它正在下载。
  • @HarryBeasant 我认为当您的文件无法分块处理时无法做到这一点
  • 您可以修改代码以支持 Range: 标头,这样您就可以在下载文件时看到文件的进度。
【解决方案2】:

您可能会发现我感兴趣的 alpha 阶段 Bandwidth 项目。可能需要更多的工作,但已经有很多有趣的东西了。我认为它还没有 F/OSS 许可证。如果你想让我给它,请联系我!

【讨论】:

    【解决方案3】:

    我想知道是否已经编写了任何类来限制下载速度

    现在有: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);
    

    【讨论】:

      猜你喜欢
      • 2011-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-25
      • 2016-02-03
      • 2013-03-30
      • 1970-01-01
      • 2016-04-20
      相关资源
      最近更新 更多