利用 Cookie 記住使用者偏好樣式表,實現「換膚」功能。本文重構原始範例,修正邏輯錯誤、加強安全性、採用現代化寫法。
stylesheets/style.css、style1.css、style2.css、style3.cssStyleSheet,儲存檔名(如 style1.css)saveStyleSheet.php?style=1index.php 讀取 Cookie 載入對應 CSSsaveStyleSheet.php<?php
// 允許的樣式白名單
$allowedStyles = [
1 => 'style1.css',
2 => 'style2.css',
3 => 'style3.css',
'default' => 'style.css'
];
$styleKey = isset($_GET['style']) ? $_GET['style'] : 'default';
$cssFile = $allowedStyles[$styleKey] ?? $allowedStyles['default'];
// 設定 Cookie:10 萬小時 ≈ 11 年,Path 為根目錄
setcookie('StyleSheet', $cssFile, time() + 360000000, '/');
// 重導向回前頁(或首頁)
$referer = $_SERVER['HTTP_REFERER'] ?? '/index.php';
header("Location: $referer");
exit;
index.php 載入樣式<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>主題切換示範</title>
<?php
$cssFile = $_COOKIE['StyleSheet'] ?? 'style.css';
// 安全:再次白名單驗證,防 Cookie 污染
$allowed = ['style.css', 'style1.css', 'style2.css', 'style3.css'];
if (!in_array($cssFile, $allowed)) $cssFile = 'style.css';
?>
<link rel="stylesheet" type="text/css" href="stylesheets/<?= $cssFile ?>">
</head>
<body>
<h1>歡迎來到換膚示範頁</h1>
<p>當前樣式:<strong><?= $cssFile ?></strong></p>
<nav>
<a href="saveStyleSheet.php?style=1">樣式 1</a> |
<a href="saveStyleSheet.php?style=2">樣式 2</a> |
<a href="saveStyleSheet.php?style=3">樣式 3</a> |
<a href="saveStyleSheet.php">預設樣式</a>
</nav>
</body>
</html>
stylesheets/style1.cssbody { background: #f0f8ff; color: #1a1a2e; font-family: 'Microsoft JhengHei', sans-serif; }
h1 { border-bottom: 2px solid #4a90d9; }
a { color: #4a90d9; }
// 資料庫儲存主題設定
themes table: id, name, css_path, is_active, config_json
// 使用者偏好表
user_preferences: user_id, theme_id, custom_css
// 後台可視化編輯器:SCSS 變數編譯、即時預覽
// JavaScript 版
function switchTheme(cssFile) {
document.getElementById('theme-link').href = 'stylesheets/' + cssFile;
document.cookie = 'StyleSheet=' + cssFile + ';path=/;max-age=315360000';
}
// HTML
:root {
--bg-color: #ffffff;
--text-color: #333333;
--primary-color: #007bff;
}
[data-theme="dark"] {
--bg-color: #1a1a2e;
--text-color: #eaeaea;
--primary-color: #4a90d9;
}
// JS 切換:document.documentElement.setAttribute('data-theme', 'dark')
Cookie 換膚核心邏輯:參數驗證 → 設定 Cookie → 重導向 → 讀取 Cookie 載入 CSS。現代專案建議升級為 CSS 變數 + JS 即時切換 + 後端儲存偏好 架構,提供無縫體驗與跨裝置同步。