PHP code example of ranetrace / laravel-cloudflare

1. Go to this page and download the library: Download ranetrace/laravel-cloudflare 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/ */

    

ranetrace / laravel-cloudflare example snippets


return [
    'cache' => [
        // Cache store to use for the volatile "current" list (null = default store)
        'store' => env('CLOUDFLARE_CACHE_STORE', null),

        // Cache keys for the "current" (refreshed, TTL'd) list.
        // NOTE: last_good no longer lives in the cache; see the "last_good" section below.
        'keys' => [
            'current' => [
                'all' => 'cloudflare:ips:current',
                'v4' => 'cloudflare:ips:v4:current',
                'v6' => 'cloudflare:ips:v6:current',
            ],
        ],

        // Time to live in seconds for the "current" list (null = forever). Default: 7 days.
        'ttl' => env('CLOUDFLARE_CACHE_TTL', 60 * 60 * 24 * 7),

        // Allow falling back to the last known good list when current is missing/expired.
        'allow_stale' => env('CLOUDFLARE_ALLOW_STALE', true),

        // Throw instead of returning [] when current, last_good and static fallback are all empty.
        'throw_on_empty' => env('CLOUDFLARE_THROW_ON_EMPTY', false),
    ],

    // Durable "last_good" store. Unlike the cache, this survives cache:clear/FLUSHDB
    // (e.g. another app flushing a shared Redis) and deploys when storage/ is shared.
    'last_good' => [
        'path' => env('CLOUDFLARE_LAST_GOOD_PATH', storage_path('laravel-cloudflare/last_good.json')),
    ],

    // HTTP client settings for fetching IP ranges from Cloudflare
    'http' => [
        'timeout' => env('CLOUDFLARE_HTTP_TIMEOUT', 10), // seconds
        // [attempts, sleepMilliseconds]
        'retry' => [env('CLOUDFLARE_HTTP_RETRY_ATTEMPTS', 3), env('CLOUDFLARE_HTTP_RETRY_SLEEP', 200)],
        'user_agent' => env('CLOUDFLARE_HTTP_USER_AGENT', 'Laravel-Cloudflare-IP-Fetcher/1.0 (+https://github.com/ranetrace/laravel-cloudflare)'),
        'endpoints' => [
            'ipv4' => 'https://www.cloudflare.com/ips-v4',
            'ipv6' => 'https://www.cloudflare.com/ips-v6',
        ],
    ],

    'logging' => [
        // Whether to log a warning when a fetch to Cloudflare endpoints fails
        'failed_fetch' => env('CLOUDFLARE_LOG_FAILED_FETCH', true),

        // Warn (throttled, persisted durably) when the static fallback layer is actually
        // served — reaching it means current AND last_good are empty.
        'static_fallback' => env('CLOUDFLARE_LOG_STATIC_FALLBACK', true),
        'static_fallback_throttle' => env('CLOUDFLARE_STATIC_FALLBACK_THROTTLE', 60 * 60),
    ],

    // Static fallback IPs, used only as a cold-start floor before the first refresh.
    // Leave EMPTY to use the authoritative list bundled with the package
    // (resources/cloudflare-ips.php). A non-empty list here overrides the bundled defaults.
    'fallback' => [
        'ipv4' => [],
        'ipv6' => [],
    ],

    'diagnostics' => [
        // Enable the diagnostics route (default: false)
        'enabled' => env('CLOUDFLARE_DIAGNOSTICS_ENABLED', false),

        // Path for the diagnostics route
        'path' => env('CLOUDFLARE_DIAGNOSTICS_PATH', '/cloudflare-diagnose'),
    ],
];

use Illuminate\Support\Facades\Schedule;

Schedule::command('cloudflare:refresh')->twiceDaily(); // or ->daily(), ->hourly(), etc.

use Illuminate\Http\Middleware\TrustProxies;
use Ranetrace\LaravelCloudflare\Http\Middleware\TrustCloudflareProxies;

->withMiddleware(function (Middleware $middleware) {
    // Your other middleware interactions here...

    $middleware->replace(TrustProxies::class, TrustCloudflareProxies::class);
})

use Ranetrace\LaravelCloudflare\LaravelCloudflare;

$cloudflare = app(LaravelCloudflare::class);
$cloudflare->refresh(); // fetch and cache immediately
$v4Ips = $cloudflare->ipv4();
$v6Ips = $cloudflare->ipv6();
$allIps = $cloudflare->all();
$cacheInfo = $cloudflare->cacheInfo();

// In config/laravel-cloudflare.php
'fallback' => [
    'ipv4' => [
        '173.245.48.0/20',
        '103.21.244.0/22',
        // ... empty = use the package-bundled list
    ],
    'ipv6' => [
        '2400:cb00::/32',
        // ... empty = use the package-bundled list
    ],
],

use Ranetrace\LaravelCloudflare\Events\CloudflareIpsRefreshed;

// In your EventServiceProvider or listener
Event::listen(function (CloudflareIpsRefreshed $event) {
    // $event->ipv4 - array of IPv4 ranges
    // $event->ipv6 - array of IPv6 ranges

    Log::info('Cloudflare IPs refreshed', [
        'ipv4_count' => count($event->ipv4),
        'ipv6_count' => count($event->ipv6),
    ]);
});

use Ranetrace\LaravelCloudflare\Events\CloudflareRefreshFailed;

Event::listen(function (CloudflareRefreshFailed $event) {
    // $event->ipv4Empty - bool indicating if IPv4 fetch failed
    // $event->ipv6Empty - bool indicating if IPv6 fetch failed

    // Send alert to monitoring service
    if ($event->ipv4Empty && $event->ipv6Empty) {
        // Both failed - critical
    }
});

// config/laravel-cloudflare.php
'trust_proxies' => [
    'additional' => ['127.0.0.1', '::1'],
],

// In config/laravel-cloudflare.php or .env
'throw_on_empty' => true, // or CLOUDFLARE_THROW_ON_EMPTY=true
bash
php artisan vendor:publish --tag="laravel-cloudflare"
bash
php artisan cloudflare:refresh
bash
php artisan cloudflare:cache-info
bash
php artisan cloudflare:bundle-fallback
bash
php artisan cloudflare:refresh
bash
# Clear everything (current cache and the durable last_good store)
php artisan cloudflare:clear

# Clear only the current cache
php artisan cloudflare:clear --current

# Clear only the durable last_good store
php artisan cloudflare:clear --last-good
bash
php artisan cloudflare:bundle-fallback