HarryBeasant
HarryBeasant

Reputation: 490

Throttling download speed in PHP

I have tried the basic ones found in a Google search and even tried to write one myself, however i keep getting a problem with it. It seems to download the content server-side or something and then push it to the user, which will already have been downloaded. It will open the download page and take around 10 seconds to download and then give the file to the user in full, which makes it look like its not downloading.

I was wondering if there are any classes that have been written to throttle download speeds, or how i can fix this problem.

I have this currently;

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

Thanks!

Upvotes: 0

Views: 2231

Answers (3)

Markus Malkusch
Markus Malkusch

Reputation: 7878

I was wondering if there are any classes that have been written to throttle download speeds

Now there is: 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);

Upvotes: 0

halfer
halfer

Reputation: 20487

You might find my alpha-stage Bandwidth project of interest. Probably needs a bit more work, but there's plenty of interesting stuff already. I don't think it has a F/OSS license yet; ping me if you want me to give it one!

Upvotes: 0

TimWolla
TimWolla

Reputation: 32731

@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);
}

This will send a file with throttled download speed to the user. It works basically like this:

  • Open a file
  • loop until we are at the end
  • echo X bytes
  • flush the output to the User
  • sleep for one second.

Upvotes: 5

Related Questions