douliudong8108 2011-02-18 09:29
浏览 48
已采纳

实现图像视图数量的有效方法 - PHP

I've created a website where users can upload images and i'd like to record the total number of views for an individual image.

Now my idea on the implementation is this:

Store the ipaddress of the visitor in a session, fe:

$key = "view_img_".$img->id;  
if(!isset($_SESSION[$key]))  
{  
   $_SESSION[$key] = array();  
}  

$visitorIpAddress = $_SERVER['REMOTE_ADDRESS'];  

$found = false;  

foreach($ip in $_SESSION[$key])  
{
   if($ip == $visitorIpAdress)  
   {  
      $found = true; //visitor has visited before in the livespan of this session  
      break;  
   }  
}  

if(!$found)  
{  
   //do sql update query for the number of views for this image  
   $sql = mysql_query("UPDATE ") //etc.  

   //Add this ip to the list in the session  
   $_SESSION[$key][] = $visitorIpAdress;  
}  

Now my problem is this:

I'd like it to clear a visitor's ipaddress inside the $_SESSION[$key] variable after a certain timelimit to clear resources.

The thing is:
Most of the visitors might only view the image once, and when a certain image gets old it might not be visited any longer, but the session will still exist.

Is there a way to define a lifespan for a specific $_SESSION variable so it resets itself? (equal to $_SESSION[$key] = null)

Or would there be a better way to implement this?

  • 写回答

2条回答 默认 最新

  • duanqi5333 2011-02-18 09:36
    关注

    What you are counting via sessions approach is number of unique views. If you just want to count the number of views, don't put too much brain and just run a query like:

    UPDATE counttable SET Views = Views + 1 Where ImageID = 123
    

    Populate the ImageID and you're good to go. KISS.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 爬取1-112页所有帖子的标题但是12页后要登录后才能 我使用selenium模拟登录 账号密码输入后 会报错 不知道怎么弄了
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点