使用 PHP 限制下载速度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4002106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:42:13  来源:igfitidea点击:

Limit download speed using PHP

phpdownloadperformance

提问by Jeremy Dicaire

I found on Google some PHP scripts to limit the download speed of a file, but the file download at 10 Mbps or if it download at 80 kbps as i set it, after 5 mb, it stops downloading.

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

Can some one tell me where I can found a good PHP download speed limit script please?

有人可以告诉我在哪里可以找到一个好的PHP下载速度限制脚本吗?

Thank you very much

非常感谢

--- Edit ---

- - 编辑 - -

Here is the code :

这是代码:

<?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.');
}
?>

回答by kijin

The reason your download stops after 5MB is because it takes over 60 seconds to download 5MB at 80KB/s. Most of those "speed limiter" scripts use sleep()to pause for a while after sending a chunk, resume, send another chunk, and pause again. But PHP will automatically terminate a script if it's been running for a minute or more. When that happens, your download stops.

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

You can use set_time_limit()to prevent your script from being terminated, but some web hosts will not allow you to do this. In that case you're out of luck.

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

回答by softwarefreak

A second is too much time, it will make clients think that the server is unresponsive and prematurely end the download. Change sleep(1)to usleep(200):

一秒钟时间太长,会让客户端认为服务器没有响应,提前结束下载。更改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);

回答by PsyKzz

I tried my hand at a custom class that can help you deal with rate limiting downloads, you could try the following?

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

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.
     }
  }

I've hosted the file as a gist aswell on github here. - https://gist.github.com/3687527

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

回答by Kalanj Djordje Djordje

Downloader class is good but have one problem if you have two downloads at same time, you will lose max_execution_timevalue.

下载器类很好,但是如果您同时下载两个,则有一个问题,您将失去max_execution_time价值。

Some example:

一些例子:

Download first file(size = 1mb; download time 100 seconds )

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

After one second download second file ( size = 100 mb; dowload time = 10000 seconds)

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

First download set max_execution_timeto 0

第一次下载设置max_execution_time为 0

Second remeber _oldMaxExecTimeas 0

第二个记住_oldMaxExecTime为 0

First download end and return max_execution_timeto old value

第一次下载结束并返回max_execution_time旧值

Second download end and return max_execution timeto 0

第二次下载结束返回max_execution time0

回答by stefcud

try this: http://labs.easyblog.it/download-limiter-php/

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

using pv unix command for best for greater precision in the bandwidth

使用 pv unix 命令以获得最佳带宽精度

回答by Markus Malkusch

First of all max_execution_timeis the execution time of your script. Sleeping is not part of it.

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

Regarding speed limiting you could use something like a Token bucket. I've put everything into one convenient library for you: 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);