PHP code example of maba / gentle-force

1. Go to this page and download the library: Download maba/gentle-force 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/ */

    

maba / gentle-force example snippets




use Maba\GentleForce\RateLimit\UsageRateLimit;
use Maba\GentleForce\RateLimitProvider;
use Maba\GentleForce\Throttler;
use Maba\GentleForce\Exception\RateLimitReachedException;

$rateLimitProvider = new RateLimitProvider();
$rateLimitProvider->registerRateLimits('credentials_error', [
    // allow 3 errors per hour; 2 additional errors if no errors were made during last hour
    (new UsageRateLimit(3, 3600))->setBucketedUsages(2),
    // allow 10 errors per day
    new UsageRateLimit(10, 3600 * 24),
]);
$rateLimitProvider->registerRateLimits('api_request', [
    // - allow 10 requests each minute;
    // - user can "save up" hour of usage if not using API.
    //   This means up to 610 requests at once, after that - 10 requests per minute,
    //   which could again save-up up to 610.
    (new UsageRateLimit(10, 60))->setBucketedPeriod(3600),
]);

$throttler = new Throttler(new \Predis\Client([
    'host' => '127.0.0.1',
]), $rateLimitProvider);

// rate limiting:
try {
    $result = $throttler->checkAndIncrease('api_request', $_SERVER['REMOTE_ADDR']);
    header('Requests-Available', $result->getUsagesAvailable());
    
} catch (RateLimitReachedException $exception) {
    header('Wait-For', $exception->getWaitForInSeconds(), 429);
    return;
}

// brute-force limiting:
try {
    // we must increase error count in-advance before even checking credentials
    // this avoids race-conditions with lots of requests
    $credentialsResult = $throttler->checkAndIncrease('credentials_error', $_POST['username']);
} catch (RateLimitReachedException $exception) {
    echo sprintf('Too much password tries for user. Please try after %s seconds', $exception->getWaitForInSeconds());
    return;
}

$credentialsValid = checkCredentials($_POST['username'], $_POST['password']);

if ($credentialsValid) {
    // as we've increased error count in advance, we need to decrease it if everything went fine
    $credentialsResult->decrease();
    
    // log user into system
}

vendor/bin/php-cs-fixer fix --config=.php_cs