PHP code example of reactphp-x / limiter

1. Go to this page and download the library: Download reactphp-x/limiter library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

reactphp-x / limiter example snippets



use ReactphpX\Limiter\RateLimiter;
use function React\Async\async;
use function React\Async\await;

// Allow 150 requests per hour (the Twitter search limit). Also understands
// 'second', 'minute', 'day', or a number of milliseconds
$limiter = new RateLimiter(150, "hour");

async (function sendRequest() {
  // This call will throw if we request more than the maximum number of requests
  // that were set in the constructor
  // remainingRequests tells us how many additional requests could be sent
  // right this moment
    $remainingRequests = await($limiter->removeTokens(1));
    callMyRequestSendingFunction(...);
})();

use ReactphpX\Limiter\RateLimiter;
use function React\Async\async;
use function React\Async\await;

$limiter = new RateLimiter(1, 250);

async(function sendMessage() {
    $remainingMessages = await($limiter->removeTokens(1));
    callMyMessageSendingFunction(...);
})();

use ReactphpX\Limiter\RateLimiter;
use function React\Async\async;
use function React\Async\await;

$limiter = new RateLimiter(
    150,
    "hour",
    true
);

async(function requestHandler(request, response) {
  // Immediately send 429 header to client when rate limiting is in effect
  $remainingRequests = await($limiter->removeTokens(1));
  if ($remainingRequests < 0) {
    $response.writeHead(429, {'Content-Type': 'text/plain;charset=UTF-8'});
    $response.end('429 Too Many Requests - your IP is being rate limited');
  } else {
    callMyMessageSendingFunction(...);
  }
})();

use ReactphpX\Limiter\RateLimiter;
use function React\Async\async;
use function React\Async\await;

$limiter = new RateLimiter(10,"second");

if ($limiter->tryRemoveTokens(5))
  echo('Tokens removed');
else
  echo('No tokens removed');

use ReactphpX\Limiter\RateLimiter;
use function React\Async\async;
use function React\Async\await;

$limiter = new RateLimiter(1, 250);

// Prints 1 since we did not remove a token and our number of tokens per
// interval is 1
echo($limiter->getTokensRemaining());

use ReactphpX\Limiter\TokenBucket;
use function React\Async\async;
use function React\Async\await;

define("BURST_RATE", 1024 * 1024 * 150); // 150KB/sec burst rate
define("FILL_RATE", 1024 * 1024 * 50); // 50KB/sec sustained rate

// We could also pass a parent token bucket in to create a hierarchical token
// bucket
// bucketSize, tokensPerInterval, interval
const bucket = new TokenBucket(
  BURST_RATE,
  FILL_RATE,
  "second"
);

async(function handleData($myData) use ($bucket) {
  await($bucket->removeTokens(strlen($myData));
  sendMyData($myData);
})();