PHP Cookie记录用户历史浏览信息的代码

时间:2022-08-22 11:33:28

【基础】

Cookie常用方法:

$_COOKIE[‘RecordLuHuiDUDU'] 得到Cookie
setcookie(‘RecordLuHuiDUDU',”,time()-3600*24*30); setcookie(字段名,数据,过期时间); 设置Cookie

【注意】

重新设置Cookie需要使之前的Cookie失效,删除Cookie也是同样的方法:
setcookie(‘RecordLuHuiDUDU',”,time()-3600*24*30);

【代码示例】

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
   * 将用品id存入Cookie中
   *
   * @param $id
   * @return bool
   */
  public function setCookieRecord($id){
    $data = null;
    if(!isset($_COOKIE['RecordLuHuiDUDU'])){
      if(!empty($id)) {
        $data[0] = array(
          'id' = $id,
          'time' = date('Y-m-d H:i:s', time())
        );
      }else{
        return false;
      }
    }else{
      if(!empty($id)) {
        $data = $_COOKIE['RecordLuHuiDUDU'];
        setcookie('RecordLuHuiDUDU','',time()-3600*24*30);
        $data = json_decode($data, true);
        $num = count($data);
        //判断是否重复
        $judge = false;
        foreach($data as $index => $value){
          if($data[$index]['id'] == $id){
            $data[$index]['time'] = date('Y-m-d H:i:s', time());
            $judge = true;
          }
        }
 
        if($judge){
          setcookie('RecordLuHuiDUDU',json_encode($data),time()+3600*24*30);
          return true;
        }
 
        if($num == 10){
          for($i = 0; $i < 9; $i++){ $data[$i] = $data[$i+1]; } $data[9] = array( 'id' => $id,
            'time' => date('Y-m-d H:i:s', time())
          );
        }
        if($num <10){ $data[$num] = array( 'id' => $id,
            'time' => date('Y-m-d H:i:s', time())
          );
        }else {
          return false;
        }
      }
    }
    setcookie('RecordLuHuiDUDU',json_encode($data),time()+3600*24*30);
    return true;
  }

本文出自 IT985博客