设置 cookie 以使用 PHP 控制内容



我正在使用cookie在网页顶部显示隐私警报,由于某种原因,它仅适用于第二次单击按钮而不是第一次。

谁能明白为什么会这样?

用于测试的 Cookie 设置为 10 秒。

谢谢

John

<?php
echo "Cookie: ".$_COOKIE['privacy_warning'];
if (isset($_POST['privacy_button'])) {
setcookie('privacy_warning', true,  time()+10); // 10 seconds
}
if (!isset($_COOKIE['privacy_warning'])):
?>
<p class="text-center alt">We use cookies to make interactions with our websites and services easy and meaningful, to better understand how they are used and to tailor advertising. You can read more and make your cookie choices <a href="../privacy/" style="color:white;"><u>here</u></a>. By continuing to use this site you are giving us your consent to do this.<br></p>
<form action="index.php" method="post" >
<div class="row">
<div class="text-center large-12 columns">
<button class="button tiny success" type="submit" name="privacy_button">ACCEPT</button>
</div>
</div>
</form>
<?php
endif;
?>

实际上,这不是问题,这是cookie的工作方式。

Cookie

是使用 Set-Cookie HTTP 标头设置的,该标头以 HTTP 形式发送 来自 Web 服务器的响应。

https://en.wikipedia.org/wiki/HTTP_cookie#Implementation

假设你调用索引.php并在其中设置了一个cookie,为什么它在同一个PHP脚本中不可用?由于服务器一次发送标头和正文,因此没有"嘿,先发送此cookie标头,然后再执行其他操作"。当 PHP 脚本结束时,客户端会收到 cookie 并发送其标头 + 正文。

要解决您的问题,您可以这样做:

<?php
echo "Cookie: ".$_COOKIE['privacy_warning'];
$privacy_warning = false;
if (isset($_POST['privacy_button'])) {
setcookie('privacy_warning', true,  time()+10); // 10 seconds
$privacy_warning = true;
}
if (!privacy_warning):
?>
<p class="text-center alt">We use cookies to make interactions with our websites and services easy and meaningful, to better understand how they are used and to tailor advertising. You can read more and make your cookie choices <a href="../privacy/" style="color:white;"><u>here</u></a>. By continuing to use this site you are giving us your consent to do this.<br></p>
<form action="index.php" method="post" >
<div class="row">
<div class="text-center large-12 columns">
<button class="button tiny success" type="submit" name="privacy_button">ACCEPT</button>
</div>
</div>
</form>
<?php
endif;
?>

你的代码没问题 我运行下面的代码,它工作正常:

<?php
echo "Cookie: ".$_COOKIE['privacy_warning'] . " done n";
setcookie('privacy_warning', 'ohuuuum',  time()+10);
if (!isset($_COOKIE['privacy_warning'])):
?>
<p class="text-center alt">We use cookies to make interactions with our websites and services easy and meaningful, to better understand how they are used and to tailor advertising. You can read more and make your cookie choices <a href="../privacy/" style="color:white;"><u>here</u></a>. By continuing to use this site you are giving us your consent to do this.<br></p>
<form action="index.php" method="post" >
<div class="row">
<div class="text-center large-12 columns">
<button class="button tiny success" type="submit" name="privacy_button">ACCEPT</button>
</div>
</div>
</form>
<?php
endif;
?>

我在运行时运行此代码,我的cookie设置为"ohuuuum",当我重新加载页面时,结果是===> 饼干:ohuuuum 完成

最新更新