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 用Multisim设计汽车尾灯控制电路
  • ¥15 关于#java#的问题,请各位专家解答!(开发工具-eclipse)
  • ¥100 求用matlab求解上述微分方程的程序代码
  • ¥15 MAC安装佳能LBP2900驱动的网盘提取码
  • ¥400 微信停车小程序谁懂的来
  • ¥15 ATAC测序到底用什么peak文件做Diffbind差异分析
  • ¥15 安装ubantu过程中第一个vfat 文件挂载失败
  • ¥20 GZ::CTF如何兼容一些靶机?
  • ¥15 etcd集群部署问题
  • ¥20 谁可以帮我一下问一下各位