目前与我在我的网站的cookies打转转,我做的第一件事就是运行检查,以用户是否有饼干,如果他们不我显示问心无愧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');
    }
}

基本上指数()函数的校验和的createCookie创建一个新的cookie,任何一个可以看到的任何问题?

有帮助吗?

解决方案

在您的createCookie的功能,调用setCookie方法不会值立即添加到$ _COOKIE超全局 - 当有人要求该数组只持有本饼干(但你可以在阵列中反正你的新的Cookie值存储)

另外,如果你想它被破坏,当浏览器退出的会话cookie,指定null为到期时间。另外,只要使用PHP内置的会话。

其他提示

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

setcookie("bangUser", $unique, time() + (60*60*24*30), "/");
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top