I was given a task to restrict number of downloads , divide the total bandwidth into 2 groups and control the speed of the downloads. So i came up with the idea of doing it with PHP cause mod_bandwidth or mod_throttle werent tailored for the job. Here is the part where i attempt to control the speed of the download.
<?
$filedownload = "files/abc.exe";
$time = 10000;
$obytes = 150*1024; //150k download speed restriction
$fd = fopen ($filedownload, "rb");
while (!feof ($fd)) {
list($usec, $sec) = explode(" ", microtime());
$time_start = $usec + $sec;
$bytes = ceil($obytes/100);
echo fread($fd, $bytes);
flush();
if($time < 10000) usleep(10000-$time);
$i++;
list($usec, $sec) = explode(" ", microtime());
$time_end = $usec + $sec;
$time =ceil(($time_end - $time_start)*1000000)+10;
}
fclose ($fd);
?>
Basically we know how many max bytes we need to send per sec , so we calculate the time in microseconds it took for the code iteration to take place and deduct that time from 1 sec and usleep it for that long , if it took more than 1 sec to complete the iteration ( for example the user is on dialup and cannt receive 150k per sec) than dont put in the delay.
Hope this helps someone. You can find more PHP tips on my site but this one had to be shared in a better way :)
|