電商商品頁記錄最近瀏覽的 5 項商品,跨 Session 保留 (30 天),新瀏覽移至最前,去重,超過 5 筆移除最舊。
<?php
class BrowseHistory {
const COOKIE_NAME = 'browse_history';
const MAX_ITEMS = 5;
const TTL = 2592000; // 30 天
/** 記錄瀏覽
* @param array $item ['id'=>123, 'name'=>'商品名', 'url'=>'/p/123', 'img'=>'/img.jpg', 'price'=>99]
*/
public static function push(array $item) {
// 必要欄位檢查
if (empty($item['id'])) return;
$history = self::getAll();
// 去重:移除相同 id
$history = array_values(array_filter($history, fn($v) => $v['id'] != $item['id']));
// 新增至最前
array_unshift($history, $item);
// 截取前 MAX_ITEMS
$history = array_slice($history, 0, self::MAX_ITEMS);
self::save($history);
}
/** 取得歷史陣列 (最新在前) */
public static function getAll(): array {
if (empty($_COOKIE[self::COOKIE_NAME])) return [];
$data = @unserialize($_COOKIE[self::COOKIE_NAME]);
return is_array($data) ? $data : [];
}
private static function save(array $data) {
setcookie(
self::COOKIE_NAME,
serialize($data),
time() + self::TTL,
'/', // path
'', // domain
true, // secure (HTTPS)
true // httponly
);
}
public static function clear() {
self::save([]);
}
}
// 在商品頁呼叫
// BrowseHistory::push(['id'=>$goods->id, 'name'=>$goods->name, 'url'=>$goods->url, 'img'=>$goods->thumb, 'price'=>$goods->price]);
// 前端顯示 (側邊欄)
$history = BrowseHistory::getAll();
if ($history) {
echo '<div class="history"><h3>最近瀏覽</h3><ul>';
foreach ($history as $item) {
echo '<li><a href="' . htmlspecialchars($item['url']) . '">';
echo '<img src="' . htmlspecialchars($item['img']) . '" alt="" width="60">';
echo '<span>' . htmlspecialchars($item['name']) . '</span>';
echo '<em>¥' . $item['price'] . '</em></a></li>';
}
echo '</ul></div>';
}
| 環節 | 處理方式 |
|---|---|
| 資料結構 | 關聯陣列,含 id/name/url/img/price 等必要欄位 |
| 去重 | array_filter 移除相同 id,array_values 重建索引 |
| 順序 | array_unshift 新增至索引 0 (最新優先) |
| 長度限制 | array_slice($arr, 0, 5) |
| 序列化 | serialize() / unserialize() (注意 PHP 版本相容性) |
| 安全 | Secure + HttpOnly Cookie,輸出時 htmlspecialchars 防 XSS |
json_encode/decode 跨語言、可讀、安全 (無反序列化風險)。