简体   繁体   中英

How to alert a user a minute before his cookie expires in PHP / Javascript?

I am looking for something where I can alert my logged-in users a minute before their cookie expires so that they save the content in the CMS before cookie expiration.. any suggestions on how I can achieve the same?

I have set the following in my auth file

setcookie("USERNAME", $user,time()+9000);
setcookie("AUTHORID", $rec["id"],time()+9000);
setcookie("AUTH", "1",time()+9000);
setcookie("RIGHTS", $rec["rights"],time()+9000);

make additional cookie with time of expiration

setcookie("expiration_time", time,time()+9000);

and after test, time of this cookie

if( $_COOKIES['expiration_time'] + 60 < time() ){
   //... you alert code 
}

How to get cookie expiration date / creation date from javascript?

It's impossible. document.cookie contains information in string like this:

key1=value1;key2=value2;...

So there isn't any information about dates.

You can pass the time expiration to the javascript. One way is to store another cookie, so you have this:

$expireAt = time() + 9000;    
setcookie("USERNAME", $user,$expireAt);
setcookie("AUTHORID", $rec["id"],$expireAt);
setcookie("AUTH", "1",$expireAt);
setcookie("RIGHTS", $rec["rights"],$expireAt);
setcookie("EXPIREAT", $expireAt, $expireAt);

Then, this function to get cookie: ( source )

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.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 "";
}

And set a timer:

let expireat = getCookie("EXPIREAT");
if (expireat) {
  let timeAlert = Number(expireat) - 60;
  setTimeout(function() {
    // Do something
  }, timeAlert);
}

Keep in mind, user can change cookie's values.

You need to that in javascript.

  1. server sets fresh expiration time for the cookie
  2. javascript with timeout executed
  3. on page reload 1,2 again
// save minute before expiration
setTimeout(saveWork, (9000-60)*1000);

function saveWork(){
    // do your stuff
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM