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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?