浏览器退出时Cookie被销毁

时间:2010-01-14 15:05:35

标签: php cookies session setcookie

我目前在我的网站上玩饼干,我做的第一件事是检查用户是否有cookie,如果他们不显示3个选项,如果他们点击它创建一个cookie,但是如果然后退出浏览器,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,任何人都可以看到任何问题吗?

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

在你的createCookie函数中,调用setCookie不会立即将值添加到$ _COOKIE超全局 - 这个数组只保存请求时存在的cookie(但你可以将新的cookie值存储在数组中)

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