本文目录导读:

在PHP中实现Cookie同意机制,通常涉及前端用户交互和后端Cookie设置,以下是几种常见的实现方式:
基础实现(JavaScript + PHP)
HTML 前端代码
<!-- Cookie同意弹窗 -->
<div id="cookie-consent" style="display: none; position: fixed; bottom: 0; left: 0; right: 0; background: #f5f5f5; padding: 15px; border-top: 1px solid #ddd; z-index: 9999;">
<p>我们使用Cookie来提供更好的网站体验,请选择是否同意使用Cookie。</p>
<button onclick="acceptCookies('all')">同意所有Cookie</button>
<button onclick="acceptCookies('necessary')">仅必要Cookie</button>
<button onclick="declineCookies()">拒绝</button>
</div>
<script>
function acceptCookies(level) {
// 设置PHP会话中的Cookie偏好
fetch('cookie_consent.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
action: 'consent',
level: level
})
})
.then(response => response.json())
.then(data => {
if (data.success) {
document.getElementById('cookie-consent').style.display = 'none';
// 根据需要设置非必要的Cookie
}
});
}
function declineCookies() {
// 拒绝Cookie
fetch('cookie_consent.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
action: 'decline'
})
})
.then(response => response.json())
.then(data => {
if (data.success) {
document.getElementById('cookie-consent').style.display = 'none';
}
});
}
// 页面加载时检查是否已同意
window.onload = function() {
fetch('check_cookie_consent.php')
.then(response => response.json())
.then(data => {
if (!data.consent) {
document.getElementById('cookie-consent').style.display = 'block';
}
});
};
</script>
PHP 后端处理 cookie_consent.php
<?php
header('Content-Type: application/json');
session_start();
$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';
$level = $input['level'] ?? 'necessary';
switch ($action) {
case 'consent':
// 存储用户选择(可以用Cookie存储)
setcookie('cookie_consent', 'accepted', time() + 365*24*60*60, '/');
setcookie('cookie_level', $level, time() + 365*24*60*60, '/');
// 存储在session中(可选)
$_SESSION['cookie_consent'] = 'accepted';
$_SESSION['cookie_level'] = $level;
echo json_encode(['success' => true]);
break;
case 'decline':
setcookie('cookie_consent', 'declined', time() + 30*24*60*60, '/');
$_SESSION['cookie_consent'] = 'declined';
echo json_encode(['success' => true]);
break;
default:
echo json_encode(['success' => false, 'message' => '无效操作']);
}
检查用户同意状态 check_cookie_consent.php
<?php
header('Content-Type: application/json');
session_start();
$consent = $_COOKIE['cookie_consent'] ?? $_SESSION['cookie_consent'] ?? 'unknown';
$level = $_COOKIE['cookie_level'] ?? $_SESSION['cookie_level'] ?? '';
echo json_encode([
'consent' => in_array($consent, ['accepted', 'declined']),
'status' => $consent,
'level' => $level
]);
进阶实现(使用Cookie类)
创建一个更完整的Cookie管理类:
<?php
class CookieManager {
private $consentKey = 'cookie_consent';
private $levelKey = 'cookie_level';
// 设置用户同意状态
public function setConsent($status, $level = 'necessary') {
$expire = $status === 'declined' ? time() + 30*24*60*60 : time() + 365*24*60*60;
setcookie($this->consentKey, $status, $expire, '/', '', true, true);
setcookie($this->levelKey, $level, $expire, '/', '', true, true);
return true;
}
// 检查用户是否同意
public function hasConsent() {
return isset($_COOKIE[$this->consentKey]);
}
// 获取同意状态
public function getConsentStatus() {
return $_COOKIE[$this->consentKey] ?? null;
}
// 获取同意级别
public function getConsentLevel() {
return $_COOKIE[$this->levelKey] ?? 'necessary';
}
// 设置特定类型的Cookie(但先检查用户权限)
public function setCookie($name, $value, $expire = 0, $type = 'necessary') {
if ($this->canSetCookie($type)) {
return setcookie($name, $value, $expire, '/', '', true, true);
}
return false;
}
// 检查是否有权限设置特定类型的Cookie
private function canSetCookie($type) {
$status = $this->getConsentStatus();
$level = $this->getConsentLevel();
if ($status === 'declined' && $type !== 'necessary') return false;
if ($status === 'accepted') {
switch ($level) {
case 'all':
return true;
case 'necessary':
return $type === 'necessary';
default:
return $type === 'necessary';
}
}
return $type === 'necessary';
}
}
使用JavaScript库(合规方案)
推荐使用成熟的解决方案:
<!-- 引入 Cookie Consent 库 -->
<script src="https://cdn.jsdelivr.net/npm/cookieconsent@3/build/cookieconsent.min.js"></script>
<script>
window.addEventListener("load", function(){
window.cookieconsent.initialise({
"palette": {
"popup": {
"background": "#000"
},
"button": {
"background": "#f1d600"
}
},
"theme": "classic",
"position": "bottom-left",
"content": {
"message": "本网站使用Cookie来提升用户体验。",
"dismiss": "同意",
"deny": "拒绝",
"link": "了解更多",
"href": "/privacy-policy"
},
"onStatusChange": function(status, chosenBefore) {
// 保存状态到服务器
fetch('/save_consent.php', {
method: 'POST',
body: JSON.stringify({
status: status,
chosenBefore: chosenBefore
})
});
},
"onRevokeChoice": function() {
// 用户撤销选择
}
})
});
</script>
最佳实践建议
GDPR合规检查清单
- ✅ 告知用户Cookie用途
- ✅ 获取明确同意
- ✅ 提供拒绝选项
- ✅ 记录用户选择
- ✅ 提供撤回机制
- ✅ 说明数据处理方式
PHP端检查函数
<?php
// 获取当前用户Cookie设置
function getUserCookieSettings() {
$settings = [
'consent_given' => false,
'consent_type' => 'none',
'necessary' => [],
'analytics' => [],
'marketing' => []
];
if (isset($_COOKIE['cookie_settings'])) {
$settings = json_decode($_COOKIE['cookie_settings'], true);
}
return $settings;
}
// 检查是否允许设置特定类型Cookie
function canUseCookieType($type) {
$settings = getUserCookieSettings();
if ($settings['consent_type'] === 'all') return true;
if ($settings['consent_type'] === 'necessary' && $type === 'necessary') return true;
return false;
}
// 根据用户设置决定是否设置Cookie
if (canUseCookieType('analytics')) {
setcookie('analytics_data', 'xxx', time() + 3600);
}
安全的Cookie设置
// 设置安全的Cookie
setcookie("cookieName", "value", [
'expires' => time() + 86400,
'path' => '/',
'secure' => true, // 仅HTTPS
'httponly' => true, // 不可通过JavaScript访问
'samesite' => 'Strict' // 防止CSRF攻击
]);
这种实现方式既能遵守GDPR等隐私法规,又能提供良好的用户体验,建议根据你的具体需求选择适合的方案。