drwkqwa82140 2012-09-29 16:39 采纳率: 0%
浏览 49
已采纳

使用WordPress设置cookie [重复]

Possible Duplicate:
Cookies aren't persisting in PHP?

My objective is: when a user visits my website landing page and chooses their city (x or y), I would like to set a cookie that remembers this choice, so next time they visit the landing page it redirects straight to their city. The code I currently have is this:

landing page:

<?php
if (isset($_COOKIE['cambridge'])) {
    header('Location: http://cambridge.guestvibe.com');
}
else if (isset($_COOKIE['oxford'])) {
    header('Location: http://oxford.guestvibe.com');
}
?>

city-specific page (one example):

<?php setcookie("Cambridge",""); ?>

I've also tried:

<?php setcookie("Cambridge",""); ?>

This isn't working for me but it's my first time working with cookies. Any idea what's wrong?

EDIT

The accepted answer solves half the problem, but for WordPress it's also necessary to add some code, explained here.

Final code is:

setcookie('city','Cambridge',time()+86400*365, "/", ".guestvibe.com");
  • 写回答

1条回答 默认 最新

  • doucheng5209 2012-09-29 17:05
    关注

    That's because with your usage of setcookie() is bound to expire when the browser is closed. setCookie has a third parameter that you should use to set when it will expire. Leaving this out defaults to when the browser is closed. Here's an example on how to set a cookie that will expire in 365 days:

    setcookie('city','Cambridge',time()+86400*365); // remember for 365 days.
    

    Then, change your code to something like this:

    if ($_COOKIE['city'] == 'Cambridge') {
        // redirect
    } else if ($_COOKIE['city'] == 'Oxford') {
        // redirect
    }
    

    For more information about setting cookies, please check the PHP documentation for setcookie.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab实现基于主成分变换的图像融合。
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊