Detailed explanation of php using cookies to store browsing records

高洛峰
Release: 2016-10-20 15:19:35
Original
1520 people have browsed it

When we are working on projects, some modules are often browsing record lists, but how do we implement the browsing record function in PHP? Now we implement it through cookies


Let’s first analyze the idea

Access The page

gets the product data list in the stored browsing history

If the currently browsed product is not in the history record, it will be added, and if it is, it will be updated

If you have a rough idea, you can look at the code directly


The complete code is as follows:

<?php
 
//如是COOKIE 里面不为空,则往里面增加一个商品ID
if (!empty($_COOKIE[&#39;SHOP&#39;][&#39;history&#39;])){
     
    //取得COOKIE里面的值,并用逗号把它切割成一个数组
    $history = explode(&#39;,&#39;, $_COOKIE[&#39;SHOP&#39;][&#39;history&#39;]);
     
    //在这个数组的开头插入当前正在浏览的商品ID
    array_unshift($history, $id);
     
    //去除数组里重复的值
    $history = array_unique($history);
    // $arr = array (1,2,3,1,3);
    // $arr = array (1,1,2,3,3);
    // $arr = array (1,2,3);
     
    //当数组的长度大于5里循环执行里面的代码
    while (count($history) > 5){
        //将数组最后一个单元弹出,直到它的长度小于等于5为止
        array_pop($history);
    }
 
 
    //把这个数组用逗号连成一个字符串写入COOKIE,并设置其过期时间为30天
    setcookie(&#39;SHOP[history]&#39;, implode(&#39;,&#39;, $history), $cur_time + 3600 * 24 * 30);
 
}else{
    //如果COOKIE里面为空,则把当前浏览的商品ID写入COOKIE ,这个只在第一次浏览该网站时发生
    setcookie(&#39;SHOP[history]&#39;, $id, $cur_time + 3600 * 24 * 30);
}
 
//以上均为记录浏览的商品ID到COOKIE里,下面将讲到怎样用这样COOKIE里的数据
 
//取得COOKIE里的数据 ,格式为1,2,3,4 这样,当然也有可以为0
$history =isset ($_COOKIE[&#39;SHOP&#39;][&#39;history&#39;]) ? $_COOKIE[&#39;SHOP&#39;][&#39;history&#39;] : 0;
 
//写SQL语句,用IN 来查询出这些ID的商品列表
$sql_history = "SELECT * FROM `goods` WHERE `goods_id` in ({$history})";
 
 
//执行SQL语句,返回数据列表
$goods_history = $db->getAll($sql_history);
if ($goods_history) {
    $tpl->assign (&#39;goods_history&#39;,$goods_history);
}
?>
Copy after login

The following is the mysql operation to obtain product information based on the storage ID. You can obtain it according to your own code, you can use the original ecology, or you can use the framework's query database method. You can modify it appropriately


Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!