PHP code example of godsdev / rate-limiter-mysql

1. Go to this page and download the library: Download godsdev/rate-limiter-mysql 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/ */

    

godsdev / rate-limiter-mysql example snippets


$conn = \GodsDev\RateLimiter\RateLimiterMysql::createConnectionObj($dbConfig);
$limiter = new \GodsDev\RateLimiter\RateLimiterMysql(
        $rate, //int
        $period, //int
        $userId, //string
        $conn // \PDO connection
);

//@todo put into PHPUnit test instead!
$stmt = $conn->prepare("SELECT NOW();");
$stmt->execute();
$row = $stmt->fetch();
$timestampPhp = date("Y-m-d H:i:s");
if($row[0] !== $timestampPhp){
    error_log("MySQL time {$row[0]} is different from PHP {$timestampPhp}");
}

//in case of identified troubles fix by some code like this
date_default_timezone_set('Europe/Prague');
/** or directly in php.ini
[Date]
date.timezone = "Europe/Prague"
**/

//For quota notification calculation
$consumedFromThePast = $limiter->getHits($timestamp);

//Increments usage in time and returns number of hits allowed (compared to increment)
$consumedAmount = $limiter->inc($timestamp, $wantToConsumeAmount);

if ($consumedAmount < 1) {
    // you must wait
} else if ($wantToConsumeAmount > $consumedAmount) {
    // it may partly be executed
} else {
    // green go
}


$config["dbConnection"] = array(
    //if you can, use localhost instead of 127.0.0.1 to speed up access on Linux. see a comment in http://php.net/manual/en/pdo.connections.php
    "dsn" => "mysql:dbname=rate_limiter_test;host=localhost",
    "user" => "root",
    "pass" => "",
);