Skip to content
KitploitKITPLOIT
StrumentiBlog
Invia
StrumentiBlog
Invia

Strumenti di Hacking, PenTest e Cybersecurity per il tuo Arsenale di Sicurezza!

Kitploit è una directory di strumenti di hacking, cybersecurity e pentesting. Scopri gli ultimi aggiornamenti dei progetti per trovare vulnerabilità, analizzare sistemi, automatizzare i test e rafforzare la tua sicurezza.

··Feed·Contatto·Privacy·© 2026 Kitploit

Directory degli strumenti

Categorie

Vedi tutte le categorie
Loading categories
limitrr-php — Migliore rate limiting in PHP con Redis. | Kitploit
Strumenti/GitHubGitHub/eddiejibson/limitrr-php
Autenticazione e AutorizzazioneScripting e AutomazioneSicurezza WebUtilità e FrameworkSicurezza delle API
GitHubeddiejibson/limitrr-php

limitrr-php

Migliore rate limiting in PHP con Redis.

Vedi Repository
2066 anni faRevisionato da Kitploit

Più Popolari

Vedi tutti →

Scopri gli strumenti più utilizzati dalla nostra community.

Esplora tutti gli strumenti

Sfoglia la nostra collezione di strumenti

Vedi tutti gli strumenti →
Condividi
chae

Rate limiting leggero in PHP usando Redis.

Limitrr PHP è fortemente ispirato alla mia altra libreria, Limitrr, creata per NodeJS. Dai un'occhiata qui

Limitrr PHP consente agli utenti di integrare facilmente il rate limiting nella propria applicazione. A differenza di altri pacchetti simili, questa utility permette di limitare non solo il numero di richieste ma anche il numero di azioni completate (ad esempio consentendo la creazione di un certo numero di account in un intervallo di tempo) e di applicare tali limitazioni con opzioni personalizzate. Inoltre, sono possibili discriminatori personalizzati: non devi più limitare in base al solo IP dell'utente.

Questa libreria fornisce anche una funzione middleware per applicare facilmente il rate limiting alle varie route che potresti avere all'interno di un progetto SlimPHP.

Se apprezzi questo progetto, per favore lascia una 🌟 su GitHub.

Le Pull Request sono benvenute

Installazione

Puoi installare la libreria limitrr-php eseguendo il seguente comando nel tuo terminale (supponendo che tu abbia installato composer)

root@kitploit:~
composer require eddiejibson/limitrr-php "^1.0"

Guida rapida

Utilizzo di base

root@kitploit:~
require "/vendor/autoload.php"; //Require composer's autoload

$options = [
    //Redis keystore information
    "redis" => [
        "host" => "666.chae.sh",
        "port" => 6379,
        "password" => "supersecret",
    ],
    "routes" => [
        "default" => [
            "requestsPerExpiry" => 5,
        ],
    ],

];

//Initialize the Limitrr class and pass the options defined above into it
//Note that the options are not required.
$limitrr = new \eddiejibson\limitrr\Limitrr($options);

//Various examples like this can be found further into the documentation,
//for each function.
$result = $limitrr->get(["discriminator" => $ip]);
echo $result["requests"] + " Requests";
echo $result["completed"] + " Completed";
//Note that this library is no means just for SlimPHP, it just happens to
//provide a middleware function for those who may need it.

//Usage within SlimPHP
$app = new Slim\App();

//Use the Limitrr SlimPHP middleware function, if you wish:
$app->add(new \eddiejibson\limitrr\RateLimitMiddleware($limitrr)); //Make sure to pass in the main Limitrr
//instance we defined above into the middleware function. This is mandatory.

//You can also add the get IP middleware function, it will append the user's real IP
//(behind Cloudflare or not) to the request.
$app->add(new \eddiejibson\limitrr\getIpMiddleware());

//Example usage within a route
$app->get("/hello/{name}", function ($request, $response, $args) {
    $name = $args["name"];
    $ip = $request->getAttribute('realip'); //Get the IP that was defined within Limitrr's get IP middleware function
    return $response->getBody()->write("Hello, ${name}. Your IP is ${ip}.");
});

//You do not have to app the middleware function to every single route, globally.
//You can do it indivually, too - along with passing options into such. Like so:
$app->get("/createUser/{name}", function ($request, $response, $args) {
    //Non intensive actions like simple verification will have a different limit to intensive ones.
    //and will only be measured in terms of each request via the middleware.
    //No further action is required.
    if (strlen($args["name"]) < 5) {
        //Dummy function creating user
        $res = $someRandomClass->registerUser();
        if ($res) {
            //Intensive actions like actually registering a user should have a
            //different limit to normal requests, hence the completedActionsPerExpiry option.
            //and should only be added to once this task has been completed fully
            //In this example, we will be limiting the amount of completed actions a certain IP can make.
            //Anything can be passed in here, however. For example, a email address or user ID.
            //$request->getAttribute('realip') was determined by calling the middleware earlier - getIpMiddleware()
            $limitrr->complete(["discriminator"] => $ip);
        }
    }
})->add(new \eddiejibson\limitrr\RateLimitMiddleware($limitrr, ["route"=>"createUser"]));
//You can also pass the route name within the limitrr middleware function

$app->run();

Ottenere il valore di una determinata chiave

limitrr->get()

Restituisce: Array

root@kitploit:~
$limitrr->get([
    "discriminator" => $discriminator, //Required
    "route" => $route, //Not required, default is assumed
    "type" => $type //Not required
]);
Parametri di ->get()

Devono essere passati alla funzione tramite un array

  • discriminator: Obbligatorio Dove discriminator è l'elemento da limitare (es. x numero di azioni completate per discriminatore)
  • route: String Da quale route devono essere recuperati i valori? Se non impostata, prenderà i conteggi dalla route default
  • type: String Invece di recuperare entrambi i valori, puoi specificare requests o completed in questa chiave e verrà restituito solo quel valore come intero.
Esempi di ->get()
root@kitploit:~
$limitrr->get([
    "discriminator" => $discriminator,
    "type" => $type,
    "route" => $route
]); //Besides discriminator, all parameters are optional.
//If type is not passed into the function, it will
//return both the amount of requests and completed actions

//Where discriminator is the thing being limited
//e.g x amount of completed actions/requests per discriminator
$limitrr->get(["discriminator" => $discriminator]);

//This tends to be the user's IP.
$limitrr->get(["discriminator" => $ip]);
//This will return both the amount of requests and completed actions stored under the
//discriminator provided in an object. You can handle like this:
$result = $limitrr->get(["discriminator" => $ip]);
echo $result["requests"] + " Requests";
echo $result["completed"] + " Completed";

//The above example would get the request and completed task count from the default
//route. If you would like to retrieve values from a different route, you can specify
//this as well. It can be done like this:
$result = $limitrr->get(["discriminator" => $ip, "route" => "exampleRouteName"]);
echo $result["requests"] . " Requests made through the route exampleRouteName";
echo $result["completed"] . " Completed Tasks made through the route exampleRouteName";

//You may also only fetch only one type of value - instead of both requests and completed.
$result = $limitrr->get(["discriminator" => $ip, "route" => "exampleRouteName", "type" => "completed"]);
echo $result["completed"] . " Completed tasks made through the route exampleRouteName";

Completare il conteggio di azioni/attività

limitrr->complete()

Restituisce: Integer

root@kitploit:~
$limitrr->get([
    "discriminator" => $discriminator, //Required
    "route" => $route, //Not required, default is assumed
]);
Parametri di ->complete()

Devono essere passati alla funzione tramite un array

  • discriminator: Obbligatorio Dove discriminator è l'elemento da limitare (es. x numero di azioni completate per discriminatore)
  • route: String In quale route devono essere inseriti i valori? Se non impostata, prenderà i conteggi dalla route default

Rimozione di valori da determinate chiavi request/completed

limitrr->reset()

Restituisce: Boolean

root@kitploit:~
$limitrr->reset([
    "discriminator" => $discriminator, //Required
    "route" => $route, //Not required, default is assumed,
    "type" => $type //Not required
]);
Parametri di ->reset()

Devono essere passati alla funzione tramite un array

  • discriminator: Obbligatorio Dove discriminator è l'elemento da limitare (es. x numero di azioni completate per discriminatore)
  • route: String Da quale route devono essere azzerati i valori? Se non impostata, azzererà i conteggi dalla route default
  • type: String Quale conteggio vuoi azzerare? requests o completed? Se non impostato, verranno rimossi entrambi.
root@kitploit:~
//Where discriminator is the thing being limited
//e.g x amount of completed actions/requests per discriminator
//This will remove both the amount of requests and completed action count
$limitrr->reset(["discriminator" => $discriminator]);

//This tends to be the user's IP.
$limitrr->reset(["discriminator" => $ip]);

//If you wish to reset counts from a particular route, this can be done as well.
//As the type is not specified, it will remove both the request and completed count
$result = $limitrr->reset([
    "discriminator" => $ip,
    "route" => "exampleRouteName"
]);
if ($result) {
    echo "Requests removed from the route exampleRouteName";
} else {
    //Do something else
}

//If you want to remove either one of the amount of requests or completed actions.
//but not the other, this can be done as well.
//The value passed in can either be "requests" or "completed".
//In this example, we will be removing the request count for a certain IP
$result = $limitrr->reset([
    "discriminator" => $ip,
    "type" => "requests"
]);
if ($result) {
    echo "Request count for the specified IP were removed"
} else {
    //do something else
}

Configurazione

redis

Obbligatorio: false

Tipo: Array o String

Descrizione: Informazioni di connessione a Redis.

Passa una stringa contenente l'URI dell'istanza Redis oppure un oggetto contenente le informazioni di connessione:

  • port: Integer Porta Redis. Predefinita: 6379
  • host: String Hostname Redis. Predefinito: "127.0.0.1"
  • password: String Password Redis. Predefinita: ""
  • database: Integer Database Redis. Predefinito: 0

Esempio di array/stringa redis da passare a Limitrr

root@kitploit:~
    //Pass in a string containing a redis URI.
    "redis" => "redis://127.0.0.1:6379/0"
    //Alternatively, use an array with the connection information.
    "redis" => [
        "port" => 6379, //Redis Port. Required: false. Defaults to 6379
        "host" => "127.0.0.1", //Redis hostname. required: False. Defaults to "127.0.0.1".
        "password" => "mysecretpassword1234", //Redis password. Required: false. Defaults to null.
        "database" => 0 //Redis database. Required: false. Defaults to 0.
    ]

options

Obbligatorio: false

Tipo: Array

Descrizione: Varie opzioni relative a Limitrr.

  • keyName: String Il nome della chiave sotto cui verranno memorizzate tutte le richieste. Serve principalmente a scopi estetici e non incide più di tanto. Tuttavia, dovrebbe essere modificato a ogni inizializzazione della classe principale per evitare conflitti. Predefinito: "limitrr"
  • errorStatusCode: Integer Codice di stato da restituire quando l'utente viene limitato. Predefinito: 429 (Too Many Requests)

Esempio di oggetto options da passare a Limitrr

root@kitploit:~
"options" => [
    "keyName" => "myApp", //The keyname all of the requests will be stored under. Required: false. Defaults to "limitrr"
    "errorStatusCode" => 429 //Should important errors such as failure to connect to the Redis keystore be caught and displayed?
]

routes

Obbligatorio: false

Tipo: Array

Descrizione: Definisci le restrizioni delle route.

All'interno dell'oggetto routes puoi definire molte route separate e impostare regole personalizzate per ciascuna. Le regole personalizzate che puoi impostare sono:

  • requestsPerExpiry: Integer Quante richieste possono essere accettate prima che l'utente venga limitato? Predefinito: 100
  • completedActionsPerExpiry: Integer Quante azioni completate possono essere accettate prima che l'utente venga limitato? Utile per determinate azioni come la registrazione di un utente: si può consentire un certo numero di richieste ma un numero diverso (ovviamente inferiore) di "azioni completate". Quindi, se utenti sono stati registrati con successo più volte di recente dallo stesso IP (o altro discriminatore), possono essere limitati. Potrebbero avere 100 richieste consentite per una certa scadenza per la validazione generale e simili, ma solo una piccola frazione di queste per procedure intensive. Predefinito: il valore di requestsPerExpiry oppure 5 se non impostato.
  • expiry: Integer Per quanto tempo devono essere memorizzate le richieste (in secondi) prima di essere azzerate? Se impostato a -1, i valori non scadranno mai e rimarranno tali indefinitamente, oppure dovranno essere rimossi manualmente. Predefinito: 900 (15 minuti)
  • completedExpiry: Integer Per quanto tempo devono essere memorizzate le "azioni completate" (come il numero di utenti registrati da un particolare IP o altro discriminatore) (in secondi) prima di essere azzerate? Se impostato a -1, tali valori non scadranno mai e rimarranno tali indefinitamente, oppure dovranno essere rimossi manualmente. Predefinito: il valore di expiry oppure 900 (15 minuti) se non impostato.
  • errorMsgs: Object Messaggi di errore separati per troppe richieste e troppe azioni completate. A loro sono state assegnate rispettivamente le chiavi "requests" e "actions". Questo verrà restituito all'utente quando viene limitato. Se nessuna stringa è stata impostata in , il valore predefinito sarà . Inoltre, se non è stato impostato un valore in , verrà usata la stringa presente in . Oppure, se anche quella non è stata impostata, sarà il suo valore.

Esempio di array routes

root@kitploit:~
"routes" => [
    //Overwrite default route rules - not all of the keys must be set,
    //only the ones you wish to overwrite
    "default" => [
        "expiry": 1000
    ],
    "exampleRoute" => [
        "requestsPerExpiry" => 100,
        "completedActionsPerExpiry" => 5,
        "expiry" => 900,
        "completedExpiry" => 900,
        "errorMsgs" => [
            "requests" => "As you have made too many requests, you are being rate limited.",
            "completed" => "As you performed too many successful actions, you have been rate limited."
        ]
    ],
    //If not all keys are set, they will revert to
    //the default values
    "exampleRoute2" => [
        "requestsPerExpiry" => 500
    ]
]
Scarica lo strumento
requests
"As you have made too many requests, you are being rate limited."
completed
requests
"As you performed too many successful actions, you have been rate limited."