1. Go to this page and download the library: Download bakaphp/phalcon-throttler 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/ */
bakaphp / phalcon-throttler example snippets
$di->setShared('redis', function () use ($config) {
$redis = new \Redis();
$redis->pconnect($config->redis->host, $config->redis->port);
$redis->auth($config->redis->password);
return $redis;
});
$throttler = $this->getDI()->get('throttler');
$rateLimit = $throttler->consume($this->request->getClientAddress());
if ($rateLimit->isLimited()) {
// Do something
}
$di->setShared('eventsManager',function() use ($di) {
$eventsManager = new \Phalcon\Events\Manager();
return $eventsManager;
});
$di->set('dispatcher', function () use ($di) {
//Create an EventsManager
$eventsManager = $di->getShared('eventsManager');
$security = new \MyNamespace\Security();
$eventsManager->attach('dispatch', $security);
$dispatcher = new \Phalcon\Mvc\Dispatcher();
$dispatcher->setEventsManager($eventsManager);
return $dispatcher;
});
namespace MyNamespace;
use Phalcon\Events\Event;
use Phalcon\Mvc\User\Plugin;
use Phalcon\Mvc\Dispatcher;
use Baka\PhalconThrottler\ThrottlerInterface;
class Security extends Plugin
{
public function beforeDispatch(Event $event, Dispatcher $dispatcher)
{
/** @var ThrottlerInterface $throttler */
$throttler = $this->getDI()->get('throttler');
$rateLimit = $throttler->consume($this->request->getClientAddress());
if ($rateLimit->isLimited()) {
$dispatcher->forward(
[
'namespace' => 'MyNamespace\Http',
'controller' => 'error',
'action' => 'ratelimited',
'params' => $rateLimit->toArray()
]
);
}
}
}
[
'hits' => (int) // Number of hits in the reference period,
'remaining' =>(int) // Remaining hits before getting rate limited,
'period' => (int) // Reference period in seconds,
'hits_per_period' => (int) // Allowed number of hits in the reference period,
'warning' => (bool) // Whether a warning has been emitted,
'limited' => (bool) // Whether the User is rate limited
]
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.