简体   繁体   中英

Throttle bandwidth in PHP

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')

It's possible if you would use the stream API (eg 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>");

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM