【问题标题】:set-cookie expiration in seconds以秒为单位设置 cookie 过期
【发布时间】:2012-11-19 15:24:47
【问题描述】:

html header Set-Cookie 函数是否接受秒过期?

header( "Set-Cookie:". $cookieName."=".$sessId."; expires=".$expireSeconds."; sessionID=".$sessId.";path=".$path."; domain=".$domain."; httponly; secure);

$expireSeconds = time()+$expireSeconds;

注意: 我不想使用 set cookie,因为我正在运行 php4 版本。 php4 在 setcookie() 函数中也不支持 httponly

【问题讨论】:

  • 不要为此使用标题。使用setcookie()
  • 您首先缺少报价,然后代码顺序错误。是的,使用setcookie()
  • 我不想使用 set cookie,因为我正在运行 php4 版本。 php4 在 setcookie() 函数中也不支持 httponly
  • $expireSeconds = time()+$expireSeconds;必须在 header( ... 之前的行中设置
  • 那么你应该真的,真的更新到 PHP 5。

标签: cookies php4


【解决方案1】:

expires 的正确日期格式是这样的:

Mon, 19 Nov 2012 15:40:59 GMT

这个格式可以用这个sn-p得到:

str_replace('+0000', 'GMT', gmdate('r'));

或者:

gmdate('D, d M Y H:i:s T');

未来 30 天的到期日期可以通过:

$expires = str_replace('+0000', 'GMT', gmdate('r', strtotime('+30 days')));

max-age 可用于指定 cookie 的过期时间(以秒为单位);正如here 所解释的那样,这并不是在所有浏览器之间都可移植的。

【讨论】:

  • @AlvinWong 不,那是 >= 5.1.1 :)
  • "l, d-M-y H:i:s T" 怎么样?
  • @AlvinWong 该格式已过时,首选 RFC 822 格式。
【解决方案2】:

如果您自己编写标题,则需要以这种格式提供日期:

DAY, DD-MMM-YYYY HH:MM:SS GMT
DAY
    The day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat).
DD
    The day in the month (such as 01 for the first day of the month).
MMM
    The three-letter abbreviation for the month (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec).
YYYY
    The year.
HH
    The hour value in military time (22 would be 10:00 P.M., for example).
MM
    The minute value.
SS
    The second value.

但是,如果您使用 PHP 的 setcookie() 函数,日期需要是 Unix 时间戳 您可以使用 mktime()。 time()+60*60*24*30 将设置 cookie 在 30 天内过期。如果设置为 0 或省略,cookie 将在会话结束时(浏览器关闭时)过期。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-03
    • 1970-01-01
    • 2011-03-18
    • 2011-07-30
    • 2011-11-23
    相关资源
    最近更新 更多