Limit download speed using PHP

前端 未结 6 2370
北荒
北荒 2020-12-02 13:37

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 dow

6条回答
  •  醉酒成梦
    2020-12-02 14:18

    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

提交回复
热议问题