Max Gunter
Max Gunter

Reputation: 213

PHP-Downloadscript - download limit doesn´t work

when i use this phpcode to download a file with a downloadspeed of 300Kb/s i use this:

 function readfile_chunked($dl_link, $filesize_file) {
  $chunksize = 300*1024; #Buffersize in Byte 
  $data = '';
  $handle = fopen($dl_link, 'rb');
    while (!feof($handle)) {
      $data = fread($handle, $chunksize);
      sleep(1);
      print $data;
      @ob_flush();
      @flush();
    }
  fclose($handle);
 }

But it doesn´t work! :-(

When i start the Download, the speed is under one KB/s and it breaks and then resume, and so on.

When i take off this "sleep(1)" in the code above, then the download starts and all is good, but it runs with fullspeed. -> logical!

Why is this?

Upvotes: 2

Views: 143

Answers (2)

Alvin Wong
Alvin Wong

Reputation: 12440

You may want to try adding @ob_flush_end() at first to disable output buffering, and remove @ob_flush() in the loop. The delay may be because of the output buffering.

You may also try replacing print with echo. You may gain some performance improvement.

Also try a smaller chunk and use usleep instead for a shorter delay time.

Upvotes: 0

Alix Axel
Alix Axel

Reputation: 154623

That looks mostly okay, however try the following:

function readfile_chunked($path, $speed)
{
    if (is_file($path) !== true)
    {
        exit('not a local file');
    }

    header('Pragma: public');
    header('Cache-Control: public, no-cache');
    header('Content-Type: application/octet-stream');
    header('Content-Length: ' . filesize($path));
    header('Content-Disposition: attachment; filename="' . basename($path) . '"');
    header('Content-Transfer-Encoding: binary');

    $handle = fopen($path, 'rb');

    while (!feof($handle))
    {
        echo fread($handle, $speed * 1024); sleep(1);

        while (ob_get_level() > 0)
        {
            ob_end_flush();
        }

        flush();
    }

    fclose($handle);
}

readfile_chunked('/path/to/your/file.ext', 300);

Upvotes: 2

Related Questions