Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Ip Blocker Laravel Package

cresjie/ip-blocker

Simple Laravel 5 IP blocker. Install via Composer, publish config, and list blocked IPs in config/cresjie/block-ip.php. When a request matches, it throws IpBlockerException so you can render a custom “blocked” view in your exception handler.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require cresjie/ip-blocker
    

    Publish the config file:

    php artisan vendor:publish --provider="Cresjie\IpBlocker\IpBlockerServiceProvider"
    
  2. Configuration: Edit config/ip-blocker.php to define:

    • blocked_ips: Array of IPs/CIDRs to block (e.g., ['192.168.1.1', '10.0.0.0/8']).
    • whitelisted_ips: Optional array of exempted IPs/CIDRs.
    • response: Custom HTTP response for blocked requests (default: 403).
  3. First Use Case: Add middleware to app/Http/Kernel.php:

    protected $middleware = [
        // ...
        \Cresjie\IpBlocker\Middleware\IpBlocker::class,
    ];
    

    Now, requests from blocked IPs will trigger the configured response.


Implementation Patterns

Core Workflow

  1. Dynamic Blocking: Use the IpBlocker facade to programmatically check/block IPs:

    use Cresjie\IpBlocker\Facades\IpBlocker;
    
    if (IpBlocker::isBlocked(request()->ip())) {
        abort(403, 'Access denied.');
    }
    
  2. Whitelisting: Override config or use runtime checks:

    if (!IpBlocker::isWhitelisted(request()->ip())) {
        IpBlocker::blockIp(request()->ip(), 3600); // Block for 1 hour
    }
    
  3. Integration with Events: Listen for ip.blocked events to log or notify:

    IpBlocker::blockIp($ip);
    // Triggered: event(new IpBlocked($ip));
    

Advanced Patterns

  • Rate Limiting + Blocking: Combine with throttle middleware to auto-block after X attempts:

    public function handle($request, Closure $next) {
        if (auth()->attempts() >= 5) {
            IpBlocker::blockIp($request->ip(), 86400);
        }
        return $next($request);
    }
    
  • GeoIP Integration: Block by country using geoip2 package:

    $geoIp = geoip()->get($request->ip());
    if ($geoIp->country->isoCode === 'RU') {
        IpBlocker::blockIp($request->ip());
    }
    
  • API-Specific Rules: Apply middleware only to API routes in RouteServiceProvider:

    $router->middleware('ip.blocker')->group(function () {
        Route::apiResource('admin', 'AdminController');
    });
    

Gotchas and Tips

Common Pitfalls

  1. CIDR Misconfiguration:

    • Ensure CIDR ranges are valid (e.g., 192.168.0.0/16, not 192.168.0.0/33).
    • Test with IpBlocker::isBlocked('192.168.1.1') before deploying.
  2. Shared Hosting IPs:

    • Shared hosting may share IPs; whitelist your server’s IP to avoid self-blocking:
      'whitelisted_ips' => ['YOUR_SERVER_IP'],
      
  3. Proxy Headers:

    • Use request()->ip() or request()->getClientIp() to handle proxies:
      $ip = request()->ip() ?? request()->header('X-Forwarded-For');
      
  4. Performance:

    • Large IP lists slow down isBlocked(). Cache results:
      Cache::remember("ip_blocked_{$ip}", 3600, fn() => IpBlocker::isBlocked($ip));
      

Debugging Tips

  • Log Blocked IPs: Add a listener to ip.blocked:

    IpBlocker::blockIp($ip);
    // Log: \Log::info("Blocked IP: {$ip}", ['user_agent' => request()->userAgent()]);
    
  • Test Locally: Use 127.0.0.1 or ::1 in blocked_ips to test without affecting production.

  • Clear Cache: After config changes, clear Laravel cache:

    php artisan cache:clear
    php artisan config:clear
    

Extension Points

  1. Custom Responses: Override the default 403 response in app/Exceptions/Handler.php:

    public function render($request, Throwable $exception) {
        if ($exception instanceof \Symfony\Component\HttpKernel\Exception\HttpException && $exception->getStatusCode() === 403) {
            return response()->view('errors.blocked', [], 403);
        }
        return parent::render($request, $exception);
    }
    
  2. Database-Backed Blocks: Store blocked IPs in a table and query dynamically:

    public function isBlocked($ip) {
        return parent::isBlocked($ip) || BlockedIp::where('ip', $ip)->exists();
    }
    
  3. IP Rotation Handling: For Tor/VPN users, block by subnet or user-agent patterns:

    if (str_contains(request()->userAgent(), 'Tor')) {
        IpBlocker::blockIp(request()->ip());
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle