Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a cookie expire in 30 seconds

Could someone update the following code to make the cookie expire in 30 seconds.

function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}
like image 768
Odyssey Avatar asked Oct 24 '11 18:10

Odyssey


People also ask

How do you make cookies expire immediately?

To easily delete any cookie, simply set its expiration date as the epoch timestamp: document. cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/"; document.

Is it possible to set a cookie without an expiration date?

Nope. That can't be done. The best 'way' of doing that is just making the expiration date be like 2100.

How long does it take for a cookie to expire?

COOKIES, COMMERCIALLY PACKAGED - UNOPENED Properly stored, a package of unopened cookies will generally stay at best quality for about 6 to 9 months.

Is cookie Max Age in seconds?

Sets the maximum age of the cookie in seconds. This will result in a cookie1 to expire in 20 seconds.


2 Answers

function createCookie(name, value) {
   var date = new Date();
   date.setTime(date.getTime()+(30*1000));
   var expires = "; expires="+date.toGMTString();

   document.cookie = name+"="+value+expires+"; path=/";
}
like image 141
evilone Avatar answered Oct 10 '22 04:10

evilone


You can specify the maximum age in seconds when setting a cookie:

function setCookie(name, value, maxAgeSeconds) {
    var maxAgeSegment = "; max-age=" + maxAgeSeconds;
    document.cookie = encodeURI(name) + "=" + encodeURI(value) + maxAgeSegment;
}

Usage:

setCookie("username", "blaise", 30);
like image 22
Blaise Avatar answered Oct 10 '22 05:10

Blaise