PHP code example of creatcode / think-throttle

1. Go to this page and download the library: Download creatcode/think-throttle 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/ */

    

creatcode / think-throttle example snippets



// 配置
return [
    // 缓存键前缀,防止键值与其他应用冲突
    'prefix' => 'throttle_',
    // 缓存的键,true 表示使用来源ip
    'key' => true,
    // 要被限制的请求类型, eg: GET POST PUT DELETE HEAD
    'visit_method' => ['GET'],
    // 设置访问频率,例如 '10/m' 指的是允许每分钟请求10次。值 null 表示不限制, eg: null 10/m  20/h  300/d 200/300
    'visit_rate' => '100/m',
    // 访问受限时返回的响应
    'visit_fail_response' => function (Throttle $throttle, Request $request, int $wait_seconds) {
        return Response::create('Too many requests, try again after ' . $wait_seconds . ' seconds.')->code(429);
    },
];

'key' => function($throttle, $request) {
    $user_id = $request->session->get('user_id');
    return $user_id ;
},

'key' => function($throttle, $request) {
    return '__CONTROLLER__/__ACTION__/__IP__';
},
或者直接设置:

'key' => '__CONTROLLER__/__ACTION__/__IP__',

'key' => function($throttle, $request) {
    $throttle->setRate('5/m');                      // 设置频率
    $throttle->setDriverClass(CounterSlider::class);// 设置限流策略
    return true;
},