当前位置:首页 > PHP教程 > PHP常见问题

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

【基础】

cookie常用方法:

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

【注意】

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

【代码示例】

/** * 将用品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博客



【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!