You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PHP Cookies存储用户深色模式主题偏好并设置指定有效期

实现方案

1. 修改JavaScript切换逻辑

切换主题时同步将当前状态发送给PHP接口存储Cookie:

function myFunction() {
  var element = document.body;
  element.classList.toggle("dark-mode");
  // 获取当前主题状态:深色模式为1,浅色为0
  const themeStatus = element.classList.contains("dark-mode") ? 1 : 0;

  // 发送AJAX请求到PHP存储Cookie
  const xhr = new XMLHttpRequest();
  xhr.open("POST", "save_theme.php", true);
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xhr.send("theme_status=" + themeStatus);
}

2. 编写PHP Cookie存储接口(新建save_theme.php文件)

可自定义Cookie有效期,以下示例设置为保留30天:

<?php
// 校验参数是否存在
if (isset($_POST['theme_status'])) {
    // 过滤参数值,只允许0或1
    $themeStatus = intval($_POST['theme_status']) === 1 ? 1 : 0;
    // Cookie有效期设置:30天 = 30 * 24小时 * 60分钟 * 60秒
    $expireTime = time() + 30 * 24 * 60 * 60;
    // 第四个参数/表示Cookie全站生效
    setcookie("user_prefer_theme", $themeStatus, $expireTime, "/");
    // 可选返回操作状态
    echo json_encode(['code' => 200, 'msg' => '保存成功']);
}
?>

注意:setcookie方法必须在所有页面输出之前调用,所以save_theme.php文件开头不要留空格、HTML标签等多余内容,否则会导致Cookie设置失败。

3. 页面初始化自动加载用户主题偏好

将你的页面文件后缀改为.php,在body标签处读取Cookie自动添加对应样式类:

<body <?php if (isset($_COOKIE['user_prefer_theme']) && $_COOKIE['user_prefer_theme'] == 1) echo 'class="dark-mode"'; ?>>
<!-- 原有页面内容 -->

可选优化补充

你当前的CSS只设置了.mainSection的深色样式,如果需要全局背景生效,可以补充以下CSS:

body.dark-mode {
  background-color: black;
  color: white;
}

内容的提问来源于stack exchange,提问作者rosamaria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 13:06:03