Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set this cookie to never expire [closed]

I have a function to create a cookie passing in the name, value and expiration (in days) of the cookie.

Here is the function:

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;
}

function getCookie(c_name) {
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++) {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==c_name) {
            return unescape(y);
        }
    }
}

The function works as expected, but what do I need to do to set the cookie never expire?

like image 375
John mido Avatar asked May 17 '12 18:05

John mido


People also ask

How do I set never expiring cookie?

Syntax: document. cookie = "cookieName= true; expires=Tue, 19 Jan 2038 04:14:07 GMT"; // OR const cookieName = "something"; const cookieValue = "something"; const daysToExpire = new Date(2147483647 * 1000).

How do you keep cookies from expiring?

Use a far future date. For example, set a cookie that expires in ten years: setcookie( "CookieName", "CookieValue", time() + (10 * 365 * 24 * 60 * 60) );

How do I change cookie expiry date?

This can be done easily by adding expires=expirationDate in UTC separated by semicolon from the name=value, as seen in the following example: document. cookie = "username=Max Brown; expires=Wed, 05 Aug 2020 23:00:00 UTC"; document.

Which cookie has no expire time?

A cookie with no expiration date specified will expire when the browser is closed. These are often called session cookies because they are removed after the browser session ends (when the browser is closed).


2 Answers

There is no way to set to never expire . It's not a javascript limitation, it's just not the part of the specification of the cookie http://www.faqs.org/rfcs/rfc2965.html.

You can set to a far date in the future. for example to set it for 20years from now call setCookie with 20*365 as exdays parameter as you setCookie function expect how many days before it expires. Like follows

setCookie('cookiename','cookie_val',20*365);
like image 90
Prasenjit Kumar Nag Avatar answered Oct 08 '22 07:10

Prasenjit Kumar Nag


The variable exdays is how long it is until the cookie expires, just set that value to a couple of thousand days in your function call.

setCookie('cookiename', 'cookievalue', 10000); //expires in 10k days
like image 41
adeneo Avatar answered Oct 08 '22 07:10

adeneo