Save cookie and read its value when accessing the website to check if expired

Asked

Viewed 9,379 times

2

I need to make a script in Javascript that follows the following logic:

  1. Record a cookie with a id, that goes from 1 to 3. Along with the cookie, the day/time OR I want it to expire in 8 hours.

  2. The user, every time he enters the site, must read this cookie.

    If it is expired, you should read which id stopped (1, 2 or 3), should add 1 to the id (if 3 goes back to 1), and finally, open an automatic popup with a URL, which will be defined this way:

    • If it is id 1, open dominio.com.br/id1
    • If it is id 2, open dominio.com.br/id2
    • If it is id 3, open dominio.com.br/id3
  • Take a look at this question (http://answall.com/q/43889/129), it’s the same problem you want to solve?

2 answers

1

You must use document.cookie to create cookies as needed and the script must run on a server (like Apache for example), local access (protocol file://) usually does not work with cookies.

note that some browsers block cookies generated by http://localhost, to get around the problem use the address http://127.0.0.1

To create a cookie we must use the parameters as below:

document.cookie="chave=valor; expires=DATA PARA EXPIRAR; path=CAMINHO";

Note that maybe instead of cookies you can use localStorage and sessionStorage (https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage)

For example with sessionStorage:

// Salva dados na sessão
sessionStorage.setItem("username", "John");

// Pega os dados
alert( "username = " + sessionStorage.getItem("username"));

For example with localStorage:

// Salva dados na sessão
localStorage.setItem("username", "John");

// Pega os dados
alert( "username = " + localStorage.getItem("username"));

But like the question about cookies, I will show you an example with such, we will need two methods for this:

function getCookie(k) {
    var _c = String(document.cookie).split(";");
    var neq = k + "=";
    for(var i = 0; i < _c.length; i++) {
        var c = _c[i];

        while(c.charAt(0) === " "){
            _c[i] = _c[i].substring(1,c.length);
        }

        if (_c[i].indexOf(neq) === 0){
            return unescape(_c[i].substring(neq.length, _c[i].length));
        }
    }
    return null;
}

function setCookie(k, v, expira, path) {//expira devem ser segundos  (não será usado para a sua verificação)
    path = path || "/";

    var d = new Date();
    d.setTime(d.getTime() + (expira * 1000));

    document.cookie = escape(k) + "=" + escape(v) + "; expires=" + d + "; path=" + path;
}

To set your ID cookie, do this:

if (getCookie(id) === null) {//Se o cookie não existir
   var tempodevida = new Date();
   tempodevida.setTime(tempodevida + (1000 * 60 * 60 * 24 * 2));

   setCookie("id", "1|" + String(new Date().getTime()), tempodevida);
} else {
   ...
}
  • The string will form something like 1|1419862250858 is the first value of the ID and the long number is what we will use to compare the 8 hours.

  • String(new Date().getTime()) picks the time the cookie was created

  • This line 60 * 60 * 24 * 2 is a calculation for you to understand and modify it as needed, it says that the cookie must expire in two days (it has nothing to do with your 8 hours), because every cookie must have a life limit.

    The 1000 is why the Date works with mileseconds, the first 60 would be seconds, the second 60 would be minutes, the 24 is the amount of hours we have on the day and the 2 would be two days.

    I recommend that you change only the "2", for example you want the life time to be 15 days, do this: 1000 * 60 * 60 * 24 * 15

Now we will work the else example. To check we should use getCookie:

var meuCookie = getCookie("id");

it will return as one of these possible values 1|1419862250858, 2|1419862250858 and 3|1419862250858 (note that the 1419862250858 is just an example of time). We should "cut" the string using String.split:

meuCookie.split("|");

var id    = parseInt(meuCookie[0]);
var tempo = parseInt(meuCookie[1]);

We will have the variables id and tempo to compare according to your need, which should look something like:

Note that 1000 * 60 * 60 * 8 equals to 8 hours

var tempoAtual = new Date();
tempoAtual.setTime(tempoAtual - (1000 * 60 * 60 * 8));

if (tempo < tempoAtual) {//Se tempo for menor que o limite das 8 horas, então significa que expirou
    id++;
    if (id >= 3) {//Se id for igual a 3 volta para o 1
        id = 1;
    }
}

After this we must use window.location to redirect, it would be something like:

window.location = "http://dominio.com/id" + id;

The whole code should look like this:

function getCookie(k) {
    var _c = String(document.cookie).split(";");
    var neq = k + "=";
    for(var i = 0; i < _c.length; i++) {
        var c = _c[i];

        while(c.charAt(0) === " "){
            _c[i] = _c[i].substring(1,c.length);
        }

        if (_c[i].indexOf(neq) === 0){
            return unescape(_c[i].substring(neq.length, _c[i].length));
        }
    }
    return null;
}

function setCookie(k, v, expira, path) {//expira devem ser segundos  (não será usado para a sua verificação)
    path = path || "/";

    var d = new Date();
    d.setTime(d.getTime() + (expira * 1000));

    document.cookie = escape(k) + "=" + escape(v) + "; expires=" + d + "; path=" + path;
}

(function () {
    if (getCookie(id) === null) {
        var tempodevida = new Date();
        tempodevida.setTime(tempodevida + (1000 * 60 * 60 * 24 * 2));

        setCookie("id", "1|" + String(new Date().getTime()), tempodevida);
    } else {
        var meuCookie = getCookie("id");

        meuCookie.split("|");

        var id    = parseInt(meuCookie[0]);
        var tempo = parseInt(meuCookie[1]);
        var tempoAtual = new Date();
        tempoAtual.setTime(tempoAtual - (1000 * 60 * 60 * 8));

        if (tempo < tempoAtual) {
            id++;
            if (id >= 3) {
                id = 1;
            }
        }

        window.location = "http://dominio.com/id" + id;
    }
})();

-1

I’m not very good at this, but I think it might help you!

<?php

// Determinada um nome pro seu cookie
$cookie = "4567500";

// Verifica se o cookie nao existe
if(!isset($_COOKIE[''.$cookie.''])){

    //Resposta
    echo "Cookie Não existe";

    // Cria um cookie
    $nome = $cookie;
    $valor = "Valor Dentro do Cookie";
    $expira = time() + (8 * 3600);
    setcookie($nome, $valor, $expira);

    //Insere o poup no corpo da pagina
    include_once ("poup.php");

                                    }

elseif(isset($_COOKIE[''.$cookie.'']))
{
    //Resposta do servidor
    echo 'Cookie já existe';

    //Como o cookie existe ele não faz nenhum include
}

?>

This small code can be placed at the beginning of the page, so whenever the person enters your site this code will be processed, and the Poup will only appear if it has already passed 8hrs or if it has never entered

  • This is PHP, Fabio requested in Javascript. :\

  • If it is to use in a common site da para him to use php normally. Up because in javascript everything becomes more complicated and complex. And of course what I posted is just an alternative.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.