This article will introduce the PHP interface access frequency limit to everyone. I hope it will be helpful to friends in need!
I found that many restrictions on the Internet are only restrictions on access within 1 minute (or a certain time).
For example, if the limit is 10 times per minute, then I access 10 times in 59 seconds, and then the key expires again, and I can access it again in the next minute. This restriction is simply unreasonable.
So I have my idea.
Just upload the code.
/** * @param $uid * @return bool|int * 检测用户接口访问频率 */ function api_frequency_visits ($uid) { $key = "user:{$uid}:api:frequency"; $redis = new Redis(); $redis->connect('127.0.0.1'); $data = $redis->hGetAll($key); //需要删除的key $del_key = []; //时间内访问的总次数 $total = 0; //时间内最大访问次数 $max_frequency = 10; //当前时间 $now_time = time(); //限制时间 $limit_time = 60; foreach ($data as $time=>$count) { if ($time hDel($key, ...$del_key); } if ($total >= $max_frequency) { return false; } return $redis->hIncrBy($key, $now_time, 1); } $uid = 1; $result = api_frequency_visits($uid); if (!$result) { echo json_encode(['code'=>0, 'msg'=>'操作过于频繁', 'data'=>[]]);die; } echo json_encode(['code'=>1, 'msg'=>'', 'data'=>[ 'uid'=>$uid, 'other'=>rand() ]]);die;
The time limit and the number of times can be modified, including changing to the limit you want based on the user ID, such as IP, etc.
The key expiration time can also be added.
Recommended: "PHP Video Tutorial"
The above is the detailed content of Detailed explanation of PHP interface access frequency limit. For more information, please follow other related articles on the PHP Chinese website!

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
