Jaap Veldhorst
Jaap Veldhorst

Reputation: 31

Adding cookie expiration date

I found this javascript cookie script on SOF and it does exactly what I want. Redirecting first time visitors to a different URL. I only want it to have an expiration date of 1 day.

if (getCookie("first_visit") != "true") {
document.cookie = "first_visit=true";
location.href="http://pgklavertjevier.nl";    
}

function getCookie(cname) {
var name = cname + "=";
   var ca = document.cookie.split(';');
      for(var i = 0; i <ca.length; i++) {
         var c = ca[i];
         while (c.charAt(0)==' ') {
            c = c.substring(1);
         }
         if (c.indexOf(name) == 0) {
            return c.substring(name.length,c.length);
         }
     }
    return "";
}

Upvotes: 0

Views: 56

Answers (1)

prolific
prolific

Reputation: 775

You can set the expiration date (in your case 1 day) of cookie along with its value while creating it.

If you are creating cookies through javascript then you can use the below code:

function setCookie(name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString()) + ";path=/";
    document.cookie = name + "=" + c_value;
}

setCookie("first_visit", true, 1);

Upvotes: 1

Related Questions