【问题标题】:Cookie being destroyed when browser quits浏览器退出时cookie被销毁
【发布时间】:2011-01-05 02:51:22
【问题描述】:

我目前正在我的网站中使用 cookie,我做的第一件事是检查用户是否有 cookie,如果他们没有,我会显示一个菜单,如果他们点击它会创建一个 cookie,但有 3 个选项,但是如果然后退出浏览器cookie被破坏,这是我的代码,

function createRandomId() {
    $chars = "abcdefghijkmnopqrstuvwxyz023456789";
    srand((double)microtime() * 1000000);
    $i = 0;
    $unique = '';
    while ($i <= 7) {
        $num = rand() % 33;
        $tmp = substr($chars, $num, 1);
        $unique = $unique.$tmp;
        $i++;
    }
    return md5($unique);
}

function index() {
    // $data is the array of data that is passed to views, setup it up
    $data = array();
    // We need to setup the cookie that will be used site, this will be used to cross reference
    // The user with the options they have selected, to do this we first need to load the session model
    // Check if the user has a cookie already, if they it means they have been to the site in the last 30 days.
    if(!isset($_COOKIE['bangUser'])) {
        // Get createRandomId() method and return a unique ID for the user
        $unique = '';
        // Setting the cookie, name = bangUser, the cookie will expire after 30 days
        setcookie("bangUser", $unique, time() + (60*60*24*30));
        $data['firstTime'] = TRUE;
    } else {
        $data['notFirstTime'] = TRUE;
    }

    // Load the view and send the data from it.
    $this->load->view('base/index', $data); 
}


function createCookie() {
    // Function gets called when the user clicks yes on the firstTime menu.
    // The purpose of this function is to create a cookie for the user.
    // First we'll give them a unique ID
    $unique = $this->createRandomId();
    // With the unique ID now available we can set our cookie doing the same function as before
    setcookie("bangUser", $unique, time() + (60*60*24*30));
    // Now that the cookie is set we can do a 100% check, check that cookie is set and if it is redirect to
    // to the homepage
    if(isset($_COOKIE['bangUser'])) {
        redirect('welcome');
    }
}

基本上是 index() 函数做检查,createCookie 创建一个新的 cookie,大家能看出有什么问题吗?

【问题讨论】:

  • 你应该只使用uniqid()而不是创建你自己的、更慢的createrandomid()函数。

标签: php cookies session setcookie


【解决方案1】:

在您的 createCookie 函数中,调用 setCookie 不会立即将值添加到 $_COOKIE 超全局 - 此数组仅保存发出请求时存在的 cookie(但无论如何您都可以将新的 cookie 值存储在数组中)

此外,如果您想要在浏览器退出时销毁的会话 cookie,请将过期时间指定为 null。或者,只需使用 PHP 的内置会话。

【讨论】:

    【解决方案2】:

    您需要将setcookie的第四个参数($path)设置为您网站的绝对路径。例如:

    setcookie("bangUser", $unique, time() + (60*60*24*30), "/");
    

    【讨论】:

      猜你喜欢
      • 2018-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-19
      • 1970-01-01
      • 2015-12-13
      • 2012-08-31
      • 1970-01-01
      相关资源
      最近更新 更多