A rate limiter for Laravel

Overview

Laravel Throttle

Laravel Throttle was created by, and is maintained by Graham Campbell, and is a rate limiter for Laravel. Feel free to check out the change log, releases, security policy, license, code of conduct, and contribution guidelines.

Banner

Build Status StyleCI Status Software License Packagist Downloads Latest Version

Installation

Laravel Throttle requires PHP 7.2-8.1. This particular version supports Laravel 6-8.

Throttle L5.1 L5.2 L5.3 L5.4 L5.5 L5.6 L5.7 L5.8 L6 L7 L8
4.1
5.3
6.0
7.5
8.1

To get the latest version, simply require the project using Composer:

$ composer require "graham-campbell/throttle:^8.1"

Once installed, if you are not using automatic package discovery, then you need to register the GrahamCampbell\Throttle\ThrottleServiceProvider service provider in your config/app.php.

You can also optionally alias our facade:

        'Throttle' => GrahamCampbell\Throttle\Facades\Throttle::class,

Configuration

Laravel Throttle supports optional configuration.

To get started, you'll need to publish all vendor assets:

$ php artisan vendor:publish

This will create a config/throttle.php file in your app that you can modify to set your configuration. Also, make sure you check for changes to the original config file in this package between releases.

There is one config option:

Cache Driver

This option ('driver') defines the cache driver to be used. It may be the name of any driver set in config/cache.php. Setting it to null will use the driver you have set as default in config/cache.php. The default value for this setting is null.

Usage

Throttle

This is the class of most interest. It is bound to the ioc container as 'throttle' and can be accessed using the Facades\Throttle facade. There are six public methods of interest.

The 'get' method will create a new throttler class (a class that implements Throttler\ThrottlerInterface) from the 1-3 parameters that you pass to it. The first parameter is required and must either an instance of \Illuminate\Http\Request, or an associative array with two keys ('ip' should be the ip address of the user you wish to throttle and 'route' should be the full url you wish to throttle, but actually, for advanced usage, may be any unique key you choose). The second parameter is optional and should be an int which represents the maximum number of hits that are allowed before the user hits the limit. The third and final parameter should be an int that represents the time the user must wait after going over the limit before the hit count will be reset to zero. Under the hood this method will be calling the make method on a throttler factory class (a class that implements Factories\FactoryInterface).

The other 5 methods all accept the same parameters as the get method. What happens here is we dynamically create a throttler class (or we automatically reuse an instance we already created), and then we call the method on it with no parameters. These 5 methods are 'attempt', 'hit', 'clear', 'count', and 'check'. They are all documented bellow.

Facades\Throttle

This facade will dynamically pass static method calls to the 'throttle' object in the ioc container which by default is the Throttle class.

Throttler\ThrottlerInterface

This interface defines the public methods a throttler class must implement. All 5 methods here accept no parameters.

The 'attempt' method will hit the throttle (increment the hit count), and then will return a boolean representing whether or not the hit limit has been exceeded.

The 'hit' method will hit the throttle (increment the hit count), and then will return $this so you can make another method call if you so choose.

The 'clear' method will clear the throttle (set the hit count to zero), and then will return $this so you can make another method call if you so choose.

The 'count' method will return the number of hits to the throttle.

The 'check' method will return a boolean representing whether or not the hit limit has been exceeded.

Throttler\CacheThrottler

This class implements Throttler\ThrottlerInterface completely. This is the only throttler implementation shipped with this package, and in created by the Factories\CacheFactory class. Note that this class also implements PHP's Countable interface.

Factories\FactoryInterface

This interface defines the public methods a throttler factory class must implement. Such a class must only implement one method.

The 'make' method will create a new throttler class (a class that implements Throttler\ThrottlerInterface) from data object you pass to it. This documentation of an internal interface is included for advanced users who may wish to write their own factory classes to make their own custom throttler classes.

Factories\CacheFactory

This class implements Factories\FactoryInterface completely. This is the only throttler implementation shipped with this package, and is responsible for creating the Factories\CacheFactory class. This class is only intended for internal use by the Throttle class.

Http\Middleware\ThrottleMiddleware

You may put the GrahamCampbell\Throttle\Http\Middleware\ThrottleMiddleware middleware in front of your routes to throttle them. The middleware can take up to two parameters. The two parameters are limit and time. It may be useful for you to take a look at the source for this, read the tests, or check out Laravel's documentation if you need to.

ThrottleServiceProvider

This class contains no public methods of interest. This class should be added to the providers array in config/app.php. This class will setup ioc bindings.

Real Examples

Here you can see an example of just how simple this package is to use.

Our first example will be a super simple usage of our default middleware. This will setup a middleware for that url with a limit of 10 hits and a retention time of 1 hour.

use Illuminate\Support\Facades\Route;

Route::get('foo', ['middleware' => 'GrahamCampbell\Throttle\Http\Middleware\ThrottleMiddleware', function () {
    return 'Why herro there!';
}]);

What if we want custom limits? Easy! Laravel allows us to pass parameters to a middleware. This will setup a middleware for that url with a limit of 50 hits and a retention time of 30 mins.

use Illuminate\Support\Facades\Route;

Route::get('foo', ['middleware' => 'GrahamCampbell\Throttle\Http\Middleware\ThrottleMiddleware:50,30', function () {
    return 'Why herro there!';
}]);

What if we don't want to use the default middleware provided with this package? Well, that's easy too.

use GrahamCampbell\Throttle\Facades\Throttle;
use Illuminate\Support\Facades\Request;

// now let's get a throttler object for that request
// we'll use the same config as in the previous example
// note that only the first parameter is "required"
$throttler = Throttle::get(Request::instance(), 50, 30);

// let's check if we've gone over the limit
var_dump($throttler->check());

// we implement Countable
var_dump(count($throttler));

// there are a few more functions available
// please see the previous documentation

Also note that you can call methods straight on the factory instead of calling the get method.

use GrahamCampbell\Throttle\Facades\Throttle;
use Illuminate\Support\Facades\Request;

$request = Request::instance();

// the attempt function will hit the throttle, then return check
var_dump(Throttle::attempt($request));

// so this is the same as writing
var_dump(Throttle::hit($request)->check());

// and, of course, the same as
var_dump(Throttle::get($request)->attempt());
Further Information

There are other classes in this package that are not documented here (such as the transformers). This is because they are not intended for public use and are used internally by this package.

Security

If you discover a security vulnerability within this package, please send an email to [email protected]. All security vulnerabilities will be promptly addressed. You may view our full security policy here.

License

Laravel Throttle is licensed under The MIT License (MIT).

For Enterprise

Available as part of the Tidelift Subscription

The maintainers of graham-campbell/throttle and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

Comments
  • How do i get this up and running in Lumen?

    How do i get this up and running in Lumen?

    I've added the package and done an composer update. Added into my routeMiddleware in app.php i.e

    $app->routeMiddleware([ 'Throttle' => 'GrahamCampbell\Throttle\Http\Middleware\ThrottleMiddleware', ]);

    And added it to my route: $app->get('api','App\Http\Controllers\ApiController@index', ['middleware' => 'Throttle:1,1']);

    But nothing seems to happen. I suspect it's got to do with the vendor:publish command which doesn't exist in Lumen. No errors are thrown.

    Any chance of some tips on how to get this up and running?

    opened by jimmyjamieson 30
  • You cannot serialize or unserialize PDO instances

    You cannot serialize or unserialize PDO instances

    Trying out the project for the first time, so my apologies if these are known issues and this goes beyond the scope of what you're trying to do with it.

    If I instantiate a throttle with the following

    $request = Request::instance();
    Throttle::get($request, 5, 10);
    

    Laravel fails with the following error.

    You cannot serialize or unserialize PDO instances

    public function get($data, $limit = 10, $time = 60)
    {
        $key = md5(serialize($data).$limit.$time);
    

    Our application is configured to use the database session handler, and it seems the attempts to serialize a request object that contains this handler fails.

    bug enhancement 
    opened by astormcupdx 12
  • Throttle::attempt() goes over limit before returning

    Throttle::attempt() goes over limit before returning "false"

    With the following code:

    if (!Throttle::attempt($request, 5)) {
        throw new Exception('Over limit');
    }
    
    doSomething();
    

    The exception is not thrown on the sixth attempt as expected, but on the seventh. The issue seems related to issue #6.

    opened by dcro 11
  • Composer Laravel 4.2

    Composer Laravel 4.2

    Hello GrahamCampbell,

    Is this package already compatible with Laravel 4.2?

    Problem 1 - graham-campbell/throttle v0.2.0-alpha requires laravel/framework 4.1.* -> no matching package found. - graham-campbell/throttle v0.2.0-alpha requires laravel/framework 4.1.* -> no matching package found. - Installation request for graham-campbell/throttle 0.2.*@alpha -> satisfiable by graham-campbell/throttle[v0.2.0-alpha].

    question 
    opened by MarkVink 11
  • Throttle check function always returns true

    Throttle check function always returns true

    I have the following in my Route file,

    use GrahamCampbell\Throttle\Facades\Throttle;
    use Illuminate\Support\Facades\Request;
    
    Route::get('throttle-check', function(){
        $throttler = Throttle::get(Request::instance(), 5, 3);
        // let's check if we've gone over the limit
        var_dump($throttler->check());
        // count
        var_dump(count($throttler));
    });
    

    When I run this, it always returns bool(true) int(0) Even on the first run.

    Am I doing something wrong or is it the package?

    I am using the latest version (5.1.0) on Laravel 5.1.24 (LTS)

    opened by r-a-o 9
  • Added ttl method

    Added ttl method

    Hi there 👋 I've added a method to check for the end of the current duration. This way you will be able to add all standard rate-limit headers (X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset). It would be great if each Laravel cache implementation handles such functionality, but for now this is the best we can do. Hopefully you like it 😄

    opened by robinvdvleuten 8
  • Throttle based on a JWT token instead of IP address

    Throttle based on a JWT token instead of IP address

    I am using JWT token in header to authorize users. So I can uniquely identify a particular user with the token. Can I use this JWT token instead of IP address to identify a user. Multiple users behind a Proxy server can cause problems with IP address filtering. If I can uniquely identify a user i can set exact limits like 3 login attempts/hr. How can i do this?

    opened by rohitnaidu19 8
  • Crated TransformerFactoryInterface, and now Throttle constructor acce…

    Crated TransformerFactoryInterface, and now Throttle constructor acce…

    …pt Interface instead of TransformerFactory

    TransformerFactoryInterface is created and in case we want to create another TransformerFactory and inject it into Throttle class.

    Current TransformerFactory can only return ArrayTransformer or RequestTransformer, and it is not replacable.

    Another approach could be to create a strategy and allow TransformerFactory to return any TransformerInterface via container.

    We can discuss what is a better approach to make Transformers replaceable.

    If you ask me "Why we want another Transformers", I could say that in some cases we do not want to count by IP address, we might want to track users by own id. At the moment both transformers are able to create Data object based on IP address and route.

    This is just one step to make this package more extensible.

    opened by Djuki 7
  • not working for me

    not working for me

    i am using this code

    use GrahamCampbell\Throttle\Facades\Throttle;
    use Illuminate\Support\Facades\Request;
    
    $throttler = Throttle::get(Request::instance(), 10, 1);
    
    // let's check if we've gone over the limit
            var_dump($throttler->check());
    
    // we implement Countable
            var_dump(count($throttler));
    

    but i am not getting count and true or false for check() method. and also i am using cache with file

    opened by charanjeet5ingh 7
  • Keys do not expire because store::put() extends the key expire time

    Keys do not expire because store::put() extends the key expire time

    Hi,

    I have a middleware set to 100 hits per 2 minutes. If someone requests insane amount of api calls he'll get rate limited. All OK at this point.

    If normal users do an api requests (for example) once per 30 seconds, they'll get banned also. See why:

    When $throttle->attempt() checks if user is banned or not it calls hit() which increments the counter. Code

    The Store::put() calls MemcacheStore::put() and that one does memcached::set() Code

    Here's the problem: Memcached::set() overwrites an object hence extending its time lib info. So we increment the counter and this counter is counting hits that happened long way back than 2 minutes.

    Example: 1st hit at 10:00:00 ... key value is 1, expire time is 10:02:00 2nd hit at 10.00.30 ... key value is 2, expire time is moved to 10:02:30 due to Memcaches:set()
    3rd hit at 10:01:00 ... key value is 3, expire time is 10:03:00 ... 10th hit is at 10:05:00 ... key value is 10, expire time is again moved forward to 10:07:00

    Slowly, user will get banned, even thou he was under the rate limit set in middleware.

    Any thought on this?

    opened by RatkoR 7
  • does not have a method 'tags'

    does not have a method 'tags'

    Hi, I'm using the Laravel Framework version 4.2.11.

    And I have this error message :

    call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Cache\DatabaseStore' does not have a method 'tags'
    

    I have switched to file but I have the same :

    call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Cache\FileStore' does not have a method 'tags'
    

    Any idea ?

    opened by sirsquall 7
  • error in decimal usage with redis

    error in decimal usage with redis

    I get an error when I set the time to seconds.

    usage: ->middleware('ThrottleMiddleware:10,0.1');

    error: ERR invalid expire time in setex at /var/www/vendor/predis/predis/src/Client.php:370)

    opened by arlong87 0
Releases(v9.0.0)
Owner
Graham Campbell
OSS Maintainer | Laravel | StyleCI
Graham Campbell
Automagically generate UML diagrams of your Laravel code.

Laravel UML Diagram Generator Automagically generate UML diagrams of your Laravel code. Installation To install LTU via composer, run the command: com

Andy Abi Haidar 93 Jan 1, 2023
A fake mailer for Laravel Applications for testing mail.

MailThief MailThief is a fake mailer for Laravel applications (5.0+) that makes it easy to test mail without actually sending any emails. Note: Due to

Tighten 688 Nov 29, 2022
A toolbar for Laravel Telescope, based on the Symfony Web Profiler.

Laravel Telescope Toolbar Extends Laravel Telescope to show a powerful Toolbar See https://github.com/laravel/telescope Install First install Telescop

Fruitcake 733 Dec 30, 2022
A package to help you clean up your controllers in laravel

?? Laravel Terminator ?? ?? "Tell, don't ask principle" for your laravel controllers What this package is good for ? Short answer : This package helps

Iman 241 Oct 10, 2022
A request rate limiter for Laravel 5.

Alt Three Throttle An request rate limiter for Laravel 5. Installation This version requires PHP 7.1 or 7.2, and supports Laravel 5.5 - 5.7 only. To g

Alt Three 41 Jan 3, 2022
A rate limiter for Laravel

Laravel Throttle Laravel Throttle was created by, and is maintained by Graham Campbell, and is a rate limiter for Laravel. Feel free to check out the

Graham Campbell 673 Dec 30, 2022
Laravel Sliding Window Rate Limiter

Laravel Sliding Window Rate Limiter This package provides an easy way to limit any action during a specified time window. You may be familiar with Lar

Λгi 19 Oct 9, 2022
Fork of Symfony Rate Limiter Component for Symfony 4

Rate Limiter Component Fork (Compatible with Symfony <=4.4) The Rate Limiter component provides a Token Bucket implementation to rate limit input and

AvaiBook by idealista 4 Apr 19, 2022
A Packet Limiter plugin for PocketMine

PacketLimiter A Packet Limiter plugin for PocketMine A plugin to limit player from sending many packets. Attacker may sent a lot of packet. PocketMine

null 14 Nov 10, 2022
The GUI bandwidth limiter for iptables-mod-hashlimit

MulImiter OpenWrt bandwidth limiter through iptables firewall with PHP GUI Features Limit download speed per client/IP Limit upload speed per client/I

Teguh Santoso 13 Sep 15, 2022
Apply rate limiters to Laravel Livewire actions.

This package allows you to apply rate limiters to Laravel Livewire actions. This is useful for throttling login attempts and other brute force attacks

Dan Harrin 207 Dec 30, 2022
Library download currency rate and save in database, It's designed to be extended by any available data source.

Library download currency rate and save in database, It's designed to be extended by any available data source.

Flexmind. Krzysztof Bielecki 2 Oct 6, 2021
A functional and simple rate limit control to prevent request attacks ready-to-use for PHP.

RateLimitControl A functional and simple rate limit control to prevent request attacks ready-to-use for PHP. Features: Prepared statements (using PDO)

b(i*2)tez 5 Sep 16, 2022
Standardized wrapper for popular currency rate APIs. Currently supports FixerIO, CurrencyLayer, Open Exchange Rates and Exchange Rates API.

?? Wrapper for popular Currency Exchange Rate APIs A PHP API Wrapper to offer a unified programming interface for popular Currency Rate APIs. Dont wor

Alexander Graf 24 Nov 21, 2022
Ip2region is a offline IP location library with accuracy rate of 99.9% and 0.0x millseconds searching performance. DB file is ONLY a few megabytes with all IP address stored. binding for Java,PHP,C,Python,Nodejs,Golang,C#,lua. Binary,B-tree,Memory searching algorithm

Ip2region是什么? ip2region - 准确率99.9%的离线IP地址定位库,0.0x毫秒级查询,ip2region.db数据库只有数MB,提供了java,php,c,python,nodejs,golang,c#等查询绑定和Binary,B树,内存三种查询算法。 Ip2region特性

Lion 12.6k Dec 30, 2022
List of 77 languages for Laravel Framework 4, 5, 6, 7 and 8, Laravel Jetstream , Laravel Fortify, Laravel Breeze, Laravel Cashier, Laravel Nova and Laravel Spark.

Laravel Lang In this repository, you can find the lang files for the Laravel Framework 4/5/6/7/8, Laravel Jetstream , Laravel Fortify, Laravel Cashier

Laravel Lang 6.9k Jan 2, 2023
List of 77 languages for Laravel Framework 4, 5, 6, 7 and 8, Laravel Jetstream , Laravel Fortify, Laravel Cashier and Laravel Nova.

Laravel Lang In this repository, you can find the lang files for the Laravel Framework 4/5/6/7/8, Laravel Jetstream , Laravel Fortify, Laravel Cashier

Laravel Lang 6.9k Dec 29, 2022
A Laravel package to output a specific sql to your favourite debugging tool. The supported log output is Laravel Telescope, Laravel Log, Ray, Clockwork, Laravel Debugbar and your browser.

Laravel showsql A Laravel package to output a specific sql to your favourite debugging tool, your browser or your log file. Use case You often want to

Dieter Coopman 196 Dec 28, 2022
⚡ Laravel Charts — Build charts using laravel. The laravel adapter for Chartisan.

What is laravel charts? Charts is a Laravel library used to create Charts using Chartisan. Chartisan does already have a PHP adapter. However, this li

Erik C. Forés 31 Dec 18, 2022
A Laravel Starter Kit for Laravel. Built with Laravel 8.

Laravel Get Started Project Laravel Get Started Project is a basic crud app built with laravel 8. In this app a basic product crud created. Features i

Nazmul Hasan Robin 8 Nov 24, 2022