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.

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

报告相同问题?