简体   繁体   中英

Set cookie expiration date to exact time

I'm trying to make cookies expire at an exact time. For example, I wish my cookie to expire everyday at 12:00pm. As I understand you don't choose an expiration date, but a lifetime. Must I do 12pm-time() or something similar? If so, how would I achieve that?

Thank you!

You can easily use strtotime in your case.

$expire = strtotime('today 12pm');
if (time() > $expire) {
    $expire = strtotime('tomorrow 12pm');
}
setcookie('foobar', '1', $expire);

You have to give a timestamp for a cookie lifetime, so you need to find the timestamp of next noon.

$noon = strtotime('noon', time());
if($noon<=time())// Already past, get tomorrow
    $noon = strtotime('Tomorrow noon', time());
setCookie("my_cookie","my_cookie_value",$noon);

Edit: note that the second parametre in strtotime is superfluous as it is time() by default.

In PHP, time() helps you get the current time, then set dates relative to that time.

Cookies take a single point of time as the expiration date, so if you want it to be 12:00 pm, just set it as such, without taking into account the current time, which you don't care about.

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