Write cookie and read its value when accessing the web site to check if expired

2

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

  • Save a cookie with a id , which ranges from 1 to 3. Along with the cookie, the day / time OR I want it to expire in 8 hours.

  • The user, when entering the site, should read this cookie.

    If it has expired, you should read which id has stopped (1, 2 or 3), should add 1 to id (if it is 3 back to pro 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
  • asked by anonymous 26.12.2014 / 22:24

    2 answers

    1

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

      

    Note that some browsers block cookies generated by http://localhost , to work around the problem use the http://127.0.0.1

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

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

    Note that perhaps instead of cookies you can use localStorage and sessionStorage ( link )

    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 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()) takes 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 should expire in two days (there is no problem with your 8 hours), since every cookie must have a limit of life.

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

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

    Now we will work with the else of the example. To verify 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 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 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 should use window.location to redirect, it would look 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;
        }
    })();
    
        
    10.04.2015 / 18:45
    0

    I'm not very good about it, 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 been 8hrs or if it has never entered

        
    28.12.2014 / 02:42