【问题标题】:Limit number of searches per user per week in php在php中限制每个用户每周的搜索次数
【发布时间】:2018-02-07 10:06:18
【问题描述】:

我开发了一个搜索页面,只有登录的用户才能访问。但我想将每个用户的搜索限制为一周内只有 20 次。一位用户将无法搜索超过 20 次。请帮助我如何实现这一目标。

【问题讨论】:

  • 每次运行搜索时将用户 ID 和日期存储在数据库中。在运行搜索之前,从该表中选择用户 ID 与登录用户 ID 匹配且日期介于 [start of week] 和 [end of week] 之间的每条记录。如果返回的记录数 >= 20,则不要让他们搜索。

标签: php search limit


【解决方案1】:

在 users 表中实现两个列:
第 1 列:search_counts -default 0
第 2 列:search_timestamp -default 0
当用户发起搜索时:
检查 timmstap,如果它早于一周,将其设置为当前时间(现在)并将计数器设置为 1 并允许搜索,如果不是,则检查计数器是否相等的最大允许搜索然后中止它,否则增加计数器和允许搜索。 这是一个未经测试的函数,假设您将用户表中的 couner 和 timstamp 值传递给它:

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;
      }

     }
   }

用法:

//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"
 }

【讨论】:

  • 这里$ts的值是多少?
  • $ts 和 $counter 的初始值是多少?
  • 最初的 $ts 和 $counter 是什么。它们在 db 中的值是多少?
  • 两者都是零。当您更改创建两列的用户表时,您可以在数据库中将默认值设置为零,这样您就不必在代码中处理它,因为函数会设置它们.
  • 请注意,该函数返回一个布尔值,并且 timstamp 是数据库中的大整数,它是一个 Linux 时间戳(自 1970 年以来的秒数)
猜你喜欢
  • 2011-02-10
  • 1970-01-01
  • 1970-01-01
  • 2018-06-10
  • 1970-01-01
  • 2021-11-12
  • 2021-08-04
  • 1970-01-01
  • 2011-10-27
相关资源
最近更新 更多