Tuesday, August 6, 2013

Javascript and PHP Cookie Expiration Setting Technique

Javascript:

var hour = 24; // expire in 24 hours
var tm1 = new Date();
var tm2 = new Date(tm1.getTime()+3600000*hour); // 60*60*1000 = 3600000 ms
var exp = "expires = " + tm2.toUTCString();

document.cookie = 'cookiename = cookievalue;'+exp;


PHP:

$hour = 24;
setcookie("cookiename","cookievalue",time()+(3600*$hour));



For PHP technique, it has a problem. The time() gets the time of the server instead of the browser. In order to get the accurate expiration timing, one needs to either rely on Javascript to set the cookie or obtain the time zone from the browser as I mentioned in my earlier post.

No comments:

Post a Comment