简体   繁体   中英

Limit number of searches per user per week in php

I have developed a search page, which is only accessible to logged in users. But I want to limit search for each user to only 20 times in one week. One user will not be able to search for more than 20 times. Please help me how can I achieve this.

Implement two colums in the users table:
column 1 : search_counts -default 0
coumn 2 : search_timestamp -default 0
when a user initiate a search:
inspect the timmstap, if it is older than one week set it to current time (now) and set the counter to one and allow the search , if not, check the counter if its equal maximum allowed searches then abort it otherwise increment the counter and allow the search. Here is an untested function to do this assuming you pass the couner and timstamp values from the user table to it:

function search_check($counter,$ts,$max=20,$period =7) {
 $p = $period * 24 * 60 * 60;  
 $now = time();
  if(($now - $ts) >= $p ){
  //set the time stamp to now in DB
 //set the counter to 1 in DB
 return true;
  }else {
       if($counter < $max){ // 
      //increment the counter by 1 in DB
       return true;
       }else{
        return false;
      }

     }
   }

usage:

//retrieve counter and timestamp values from the DB users table
$can_search = search_check($counter,$ts);
 if($can_search){
 //search and return search result
 }else{
 echo "Sorry, maximum weekly searches reached"
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM