【问题标题】:Limit download speed using PHP使用 PHP 限制下载速度
【发布时间】:2011-04-29 11:05:48
【问题描述】:

我在 Google 上找到了一些 PHP 脚本来限制文件的下载速度,但是文件下载速度为 10 Mbps,或者如果按照我的设置以 80 kbps 的速度下载,则在 5 mb 后,它会停止下载。

谁能告诉我在哪里可以找到一个好的 PHP 下载限速脚本?

非常感谢

--- 编辑---

代码如下:

<?php
set_time_limit(0);
// change this value below
$cs_conn = mysql_connect('localhost', 'root', '');
mysql_select_db('shareit', $cs_conn);

// local file that should be send to the client
$local_file = $_GET['file'];
// filename that the user gets as default
$download_file = $_GET['file'];

// set the download rate limit (=> 20,5 kb/s)
$download_rate = 85; 
if(file_exists($local_file) && is_file($local_file)) {
    // send headers
    header('Cache-control: private');
    header('Content-Type: application/octet-stream'); 
    header('Content-Length: '.filesize($local_file));
    header('Content-Disposition: filename='.$download_file);

    // flush content
    flush();    
    // open file stream
    $file = fopen($local_file, "r");    
    while(!feof($file)) {

        // send the current file part to the browser
        print fread($file, round($download_rate * 1024));    

        // flush the content to the browser
        flush();

        // sleep one second
        sleep(1);    
    }    

    // close file stream
    fclose($file);}
else {
    die('Error: The file '.$local_file.' does not exist!');
}




if ($dl) {
} else {
    header('HTTP/1.0 503 Service Unavailable');
    die('Abort, you reached your download limit for this file.');
}
?>

【问题讨论】:

  • 你应该使用echo而不是print,它会稍微快一点
  • 感谢您的提示!

标签: php download performance


【解决方案1】:

下载 5MB 后停止下载的原因是,以 80KB/s 的速度下载 5MB 需要 60 多秒。大多数“限速器”脚本使用sleep() 在发送一个块后暂停一段时间,继续,发送另一个块,然后再次暂停。但是如果脚本运行了一分钟或更长时间,PHP 会自动终止它。发生这种情况时,您的下载将停止。

您可以使用set_time_limit() 来防止您的脚本被终止,但某些网络主机不允许您这样做。在这种情况下,你就不走运了。

【讨论】:

  • 如果我把 set_time_limit(0);在我的脚本开始时,它不会限制速度:S.. 请参阅 PHP 代码的原始帖子。
  • 我不明白使用 set_time_limit() 会如何阻止您的脚本限制下载速度。它应该做的就是防止脚本超时。脚本的核心是 sleep() 函数,它与 set_time_limit() 无关。
  • 我使用 set_time_limit 原因是 60 秒后我的下载停止... :(
  • 请记住,在设置 set_time_limit() 时,sleep() 的持续时间将在执行时间中被忽略。
  • @kijin “在那种情况下你运气不好”这很有趣。您是否偶然发现了另一种在 php 中实现速度限制的解决方案
【解决方案2】:

一秒时间太长,会让客户端认为服务器没有响应,提前结束下载。 将sleep(1) 更改为usleep(200):

set_time_limit(0);

$file = array();
$file['name'] = 'file.mp4';
$file['size'] = filesize($file['name']);

header('Content-Type: application/octet-stream');
header('Content-Description: file transfer');
header('Content-Disposition: attachment; filename="' . $file['name'] . '"');
header('Content-Length: '. $file['size']);

$open = fopen($file['name'], 'rb');
while( !feof($open) ){
    echo fread($open, 256);
    usleep(200);
}
fclose($open);

【讨论】:

    【解决方案3】:

    我尝试了一个可以帮助您处理限速下载的自定义类,您可以尝试以下方法吗?

    class Downloader {
         private $file_path;
         private $downloadRate;
         private $file_pointer;
         private $error_message;
         private $_tickRate = 4; // Ticks per second.
         private $_oldMaxExecTime; // saving the old value.
         function __construct($file_to_download = null) {
            $this->_tickRate = 4;
            $this->downloadRate = 1024; // in Kb/s (default: 1Mb/s)
            $this->file_pointer = 0; // position of current download.
            $this->setFile($file_to_download);
         }  
         public function setFile($file) {
            if (file_exists($file) && is_file($file))
               $this->file_path = $file;
            else 
               throw new Exception("Error finding file ({$this->file_path}).");
         }
         public function setRate($kbRate) {
            $this->downloadRate = $kbRate;
         }
         private function sendHeaders() {
            if (!headers_sent($filename, $linenum)) {
               header("Content-Type: application/octet-stream");
               header("Content-Description: file transfer");
               header('Content-Disposition: attachment; filename="' . $this->file_path . '"');
               header('Content-Length: '. $this->file_path);
            } else {
               throw new Exception("Headers have already been sent. File: {$filename} Line: {$linenum}");
            }
         }
         public function download() {
            if (!$this->file_path) {
               throw new Exception("Error finding file ({$this->file_path}).");
            }
            flush();    
            $this->_oldMaxExecTime = ini_get('max_execution_time');
            ini_set('max_execution_time', 0);
            $file = fopen($this->file_path, "r");     
            while(!feof($file)) {
               print fread($file, ((($this->downloadRate*1024)*1024)/$this->_tickRate);    
               flush();
               usleep((1000/$this->_tickRate)); 
            }    
            fclose($file);
            ini_set('max_execution_time', $this->_oldMaxExecTime);
            return true; // file downloaded.
         }
      }
    

    我已将文件作为要点托管在 github 上。 - https://gist.github.com/3687527

    【讨论】:

      【解决方案4】:

      Downloader 类很好,但是如果你同时有两个下载有一个问题,你会失去max_execution_time 的价值。

      一些例子:

      下载第一个文件(大小 = 1mb;下载时间 100 秒)

      一秒后下载第二个文件(大小 = 100 mb;下载时间 = 10000 秒)

      第一个下载集max_execution_time为0

      第二次记住_oldMaxExecTime为0

      第一次下载结束,将max_execution_time恢复为旧值

      第二次下载结束并返回max_execution time为0

      【讨论】:

        【解决方案5】:

        试试这个: http://labs.easyblog.it/download-limiter-php/

        使用 pv unix 命令以获得更好的带宽精度

        【讨论】:

          【解决方案6】:

          首先max_execution_time 是你的脚本的执行时间。睡觉不是其中的一部分。

          关于速度限制,您可以使用令牌桶之类的东西。我已将所有内容都放入一个方便的库中: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);
          

          【讨论】:

            【解决方案7】:

            我计划制作一个脚本,为这个问题提供不同的答案。我将允许加速,因为它变得越来越少一个文件。我可以在这里向你展示我的数学,你可以像我一样使用它。

            x=2
            l = filesize/x
            n = | current_tangent_point - %_finished |
            m = l*2 + n*2
            P = m
            L0 = P/2
            L1 = L0 + n/2
            L1 is the first derived answer to the question
            

            现在为 x 提供插件 L1

            先将两个答案除以第二个

            这是一个完美的速度梯度。

            我什至自己做了这个等式。我希望有一天能出版。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2016-04-20
              • 1970-01-01
              • 1970-01-01
              • 2015-06-09
              • 1970-01-01
              • 2016-02-03
              • 2013-03-30
              • 2012-10-11
              相关资源
              最近更新 更多