PHP使用查询字符串创建和删除cookie

时间:2012-06-29 13:11:28

标签: php

我有以下两个链接:

<a href="index.php?showDesktop=true">Show Desktop</a>

<a href="index.php?showMobile=true">Show Mobile</a>

我想要做的是,如果单击showDesktop查询,则创建一个名为showDesktop的cookie并删除co​​okie showMobile,反之亦然。到目前为止我已尝试过以下内容,但我认为我做错了。任何人都可以帮我按照提议的那样工作。

if($_GET['showDesktop']) {
    $_COOKIE('showDesktop', 'yes');
    $_COOKIE('showMobile', null);
}
else if($_GET['showMobile']) {
    $_COOKIE('showDesktop', null);
    $_COOKIE('showMobile', 'yes');
}

3 个答案:

答案 0 :(得分:1)

您使用setcookie更改Cookie数据:

setcookie('showDesktop', 'yes', time()+86400*365);
setcookie('showMobile', false);
但是,我确实认为在cookie上使用两个不同的名称是很奇怪的。考虑使用一个名为displayMode或类似的人:

setcookie('displayMode', 'desktop', time()+86400*365);

答案 1 :(得分:0)

当你使用“true”和“false”时,或许它会更好。

if($_GET['showDesktop'] == 'true') {
    setcookie('showDesktop', true);
    setcookie('showMobile', false);
}
else if($_GET['showMobile'] == 'true') {
    setcookie('showDesktop', false);
    setcookie('showMobile', true);
}

当你使用cookies时,它有点不同,如 $ _ GET $ _ POST 。您应该使用函数setcookie

答案 2 :(得分:0)

你真的需要两个饼干吗?为什么你不能使用下面的代码并解析一个cookie?

if($_GET['showDesktop']) {
    $_COOKIE('showDesktop', 'yes');
}
else if($_GET['showMobile']) {
    $_COOKIE('showDesktop', 'no');
}

您也可以通过将Cookie过期来删除Cookie

setcookie ("showDesktop", "", time() - 3600);
相关问题