Skip to content

Instantly share code, notes, and snippets.

@cengizhancaliskan
Created September 9, 2017 13:54
Show Gist options
  • Save cengizhancaliskan/7567ff4609aa8857529ae5e20d884734 to your computer and use it in GitHub Desktop.
Save cengizhancaliskan/7567ff4609aa8857529ae5e20d884734 to your computer and use it in GitHub Desktop.
php rate limiter
<?php
class RateLimit
{
protected $totalTimestamp = 0;
protected $totalCalls = 0;
protected $timestamp = 0;
protected $calls = 0;
protected $limit;
protected $frequency;
/**
*
* @param integer $limit Optional calls per frequency
* @param integer $frequency Optional frequency in seconds
*/
public function __construct($limit = 40, $frequency = 15)
{
$this->limit = $limit;
$this->frequency = $frequency;
$this->timestamp = microtime(true);
$this->totalTimestamp = microtime(true);
}
/**
* Call before every API request
*/
public function limit()
{
// Increment call counter every request
$this->calls++;
$this->totalCalls++;
// Allow burst of requests until it reaches limit threshold
if ($this->calls >= $this->limit) {
$now = microtime(true);
// Determine time taken
$duration = $now - $this->timestamp;
// Check if we have requested limit requests too fast
if ($this->frequency > $duration) {
// Wait before allowing script to continue sending requests
$wait = 1000000 * ($this->frequency - ($now - $this->timestamp));
usleep($wait);
}
// Reset current timestamp
$this->timestamp = microtime(true);
$this->totalTimestamp = $this->timestamp - $this->totalTimestamp;
// Reset call counter
$this->calls = 0;
}
}
}
$cl = new RateLimit();
for($i=1; $i<=1000; $i++) {
echo $i."\n";
$cl->limit();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment