1

Is there a way to throttle delivery of a page in pure PHP ?

I know it can be done for a download file, but I was looking for an implementation for general HTML pages.

I was looking for perhaps a header type that can be sent

header('Throttle:300kb-ps')
7
  • add sleep functionality to your code? but I don't know why you want to slow down a page Commented Aug 4, 2015 at 2:49
  • for sleep to really throttle bandwidth you'd have to have it implicitly flush, like stream the output in chunks. Otherwise it will just take longer to flush the output but the bandwidth would be the same. Commented Aug 4, 2015 at 2:55
  • This seems like it might be what you are after, php.net/manual/en/function.http-throttle.php. You may want to check the users connection speed first though, that would require an ajax request. Commented Aug 4, 2015 at 3:05
  • 1
    @ArtisiticPhoenix I think the prob with sleep is that it uses more cpu than just throttling. (I think) Commented Aug 4, 2015 at 3:19
  • 1
    I don't think you can throttle. If it's for apis and web services, I'd rate limit them. When they've done n requests in last t seconds, return Server Busy. Commented Aug 4, 2015 at 5:19

2 Answers 2

2

It's possible if you would use the stream API (e.g. fwrite()). Then you could register a token bucket stream filter. I've compiled that all for you in bandwidth-throttle/bandwidth-throttle:

use bandwidthThrottle\BandwidthThrottle;

$out = fopen("php://output", "w");

$throttle = new BandwidthThrottle();
$throttle->setRate(100, BandwidthThrottle::KIBIBYTES); // Set limit to 100KiB/s
$throttle->throttle($out);

fwrite($out, "<html>Your page</html>");
Sign up to request clarification or add additional context in comments.

Comments

1

Have a look at apache mod_ratelimit if you want to "bandwidth rate limit" pages. It works per request, so you need to figure out to whom is a request destined to and then set the limit as required.

The web server is the place to do this, you only need to use php to control it.

Also, as per my comment, if it's for APIs and web services, I'd "request rate limit" them. When they've done n requests in last t seconds, return Server Busy.

Bandwidth rate limiting only effective for large responses, like for KBs of data transfer. For small responses, like API responses, it won't have any effect.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.