Файл cookie уничтожается при выходе из браузера - PullRequest
1 голос
/ 14 января 2010

В настоящее время я играю с файлами cookie на моем веб-сайте. Сначала я проверяю, есть ли у пользователя файлы 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 ]

1 голос
/ 14 января 2010

В вашей функции createCookie вызов setCookie не сразу добавит значение к суперглобальному значению $ _COOKIE - этот массив содержит только файлы cookie, присутствующие при выполнении запроса (но вы все равно можете сохранить новое значение файла cookie в массиве)

Кроме того, если вы хотите файл cookie сеанса, который уничтожается при выходе из браузера, укажите null для времени истечения срока действия. В качестве альтернативы, просто используйте встроенные сессии PHP.

1 голос
/ 14 января 2010

Вам нужно установить четвертый параметр setcookie ($ path) в абсолютный путь вашего сайта Например:

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