Bandwidth control with PHP

Submitted on: 1/2/2015 1:04:00 PM
By: sabeen malik (from psc cd)  
Level: Intermediate
User Rating: By 4 Users
Compatibility: PHP 4.0
Views: 2880
     Its a pointer to someone looking for a bandwidth control mechanism via pure PHP implementation


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.

= "files/abc.exe";
$time = 10000;
$obytes = 150*1024; //150k download speed restriction
$fd = fopen ($filedownload, "rb");
while (!
feof ($fd)) {
$usec, $sec) = explode(" ", microtime());    
$time_start = $usec + $sec;
$bytes = ceil($obytes/100);
fread($fd, $bytes);
$time < 10000) usleep(10000-$time);
$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 :)

Other 1 submission(s) by this author


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Intermediate category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)

Other User Comments

 There are no comments on this submission.

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)

To post feedback, first please login.