简体   繁体   English

将Cookie到期日期设置为确切时间

[英]Set cookie expiration date to exact time

I'm trying to make cookies expire at an exact time. 我正在尝试使Cookie在确切的时间到期。 For example, I wish my cookie to expire everyday at 12:00pm. 例如,我希望我的Cookie每天下午12:00过期。 As I understand you don't choose an expiration date, but a lifetime. 据我了解,您选择的不是有效期,而是有效期。 Must I do 12pm-time() or something similar? 我必须做12 pm-time()或类似的事情吗? If so, how would I achieve that? 如果是这样,我将如何实现?

Thank you! 谢谢!

You can easily use strtotime in your case. 您可以根据自己的情况轻松使用strtotime

$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. 您必须提供一个cookie寿命的时间戳,因此您需要找到下一个正午的时间戳。

$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. 编辑:请注意,strtotime中的第二个参数是多余的,因为默认情况下它是time()。

In PHP, time() helps you get the current time, then set dates relative to that time. 在PHP中, 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. Cookies使用一个时间点作为到期日期,因此,如果您希望将其设置为下午12:00,则可以将其设置为这样,而不考虑当前时间,而您不必在意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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