Skip to Content

Laravel (PHP)

Die Integration von ProxyTracer in eine Laravel-Anwendung ist unglaublich einfach. Durch das Erstellen einer standardmäßigen HTTP-Middleware können Sie Ihre gesamte Anwendung global schützen oder sie selektiv auf sensible Routen (wie /login oder /checkout) anwenden.

Die Middleware

Die native Laravel-Methode $request->ip() verarbeitet automatisch die Extraktion des Load Balancers (vorausgesetzt, Ihre TrustProxies-Middleware ist richtig konfiguriert). Wir verwenden die native Http-Fassade, um die API abzufragen und die Anforderung zu verwerfen, falls sie markiert wird.
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; use Symfony\Component\HttpFoundation\Response; class ProxyTracerMiddleware { /** * Handle an incoming request. */ public function handle(Request $request, Closure $next): Response { // 1. Extract the IP (Laravel safely handles reverse proxies automatically) $ip = $request->ip(); // Skip local development IPs if (!in_array($ip, ['127.0.0.1', '::1'])) { try { // 2. Query ProxyTracer API with a strict 500ms timeout $response = Http::withToken(env('PROXYTRACER_API_KEY')) ->timeout(0.5) ->get("https://api.proxytracer.com/v1/check/{$ip}"); if ($response->successful()) { // 3. Drop the connection if a proxy is detected if ($response->json('proxy') === true) { return response()->json([ 'error' => 'Access Denied: VPN or Proxy detected.' ], 403); } } } catch (\Exception $e) { // Fail open: Log the error and allow the request to ensure uptime Log::warning("ProxyTracer validation failed: " . $e->getMessage()); } } // 4. Traffic is clean, proceed to the controller return $next($request); } }

Konfiguration

Generieren Sie die Middleware mit php artisan make:middleware ProxyTracerMiddleware.

Um sie global anzuwenden, fügen Sie sie Ihrem Middleware-Stack hinzu.

  • Laravel 11: Fügen Sie sie in Ihrer Datei bootstrap/app.php unter $middleware->append() hinzu.
  • Laravel 10 und niedriger: Fügen Sie sie dem Array $middleware in Ihrer Datei app/Http/Kernel.php hinzu.
Last updated on