简体   繁体   English

PHP中的节流带宽

[英]Throttle bandwidth in PHP

Is there a way to throttle delivery of a page in pure PHP ? 有没有办法限制纯PHP页面的交付?

I know it can be done for a download file, but I was looking for an implementation for general HTML pages. 我知道可以为下载文件完成此操作,但是我一直在寻找通用HTML页面的实现。

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() ). 有可能使用流API(例如fwrite() )。 Then you could register a token bucket stream filter. 然后,您可以注册令牌桶流过滤器。 I've compiled that all for you in bandwidth-throttle/bandwidth-throttle : 我已经为您编写了所有的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. 如果要“带宽速率限制”页面,请查看apache mod_ratelimit 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. Web服务器是执行此操作的地方,您只需要使用php进行控制即可。

Also, as per my comment, if it's for APIs and web services, I'd "request rate limit" them. 另外,根据我的评论,如果用于API和Web服务,我将“请求速率限制”。 When they've done n requests in last t seconds, return Server Busy. 当他们在过去t秒钟内完成了n次请求后,请返回服务器繁忙。

Bandwidth rate limiting only effective for large responses, like for KBs of data transfer. 带宽速率限制仅对大响应有效,例如数据传输的KB。 For small responses, like API responses, it won't have any effect. 对于较小的响应(如API响应),它不会产生任何影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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