PHP会话cookie在浏览器关闭时过期

Posted

技术标签:

【中文标题】PHP会话cookie在浏览器关闭时过期【英文标题】:PHP session cookies to expire when browser closes 【发布时间】:2015-08-12 12:36:08 【问题描述】:

我在 Wordpress 中工作,并且在我的 functions.php 页面中有以下内容。

我有 3 种不同样式的数组。我的 cookie 正在随机化。

if (isset($_COOKIE['style']))
    $style = $_COOKIE['style'];

else 
    $style = ($rand[$stylearray]);
    setcookie('style',$style,time(),COOKIEPATH,COOKIE_DOMAIN,false); 

我想设置它,以便我的 cookie ONLY 在浏览器关闭时过期。 但是,似乎在页面刷新(F5)时 cookie 会过期。

有没有办法设置它,让我的 cookie 仅在浏览器关闭时过期?

【问题讨论】:

可能很愚蠢的问题:为什么不改用$_SESSION 【参考方案1】:

http://www.w3schools.com/php/func_http_setcookie.asp 说

Optional. Specifies when the cookie expires. The value: time()+86400*30, 
will set the cookie to expire in 30 days. If this parameter is omitted 
or set to 0, the cookie will expire at the end of the session 
(when the browser closes). Default is 0

所以

setcookie('style',$style, 0 , ...); 

setcookie('style',$style, '', ...); 

必须工作。

【讨论】:

哇,这完全奏效了。我一直在做时间()+ 0。感谢您的帮助!【参考方案2】:

你需要使用session.cookie,问题是你必须修改php.ini, 根据您的虚拟主机配置,您需要创建一个 php.ini/php5.ini/.user.ini 并输入以下内容:

 session.cookie_lifetime = 0 

0 = 表示直到浏览器关闭。

【讨论】:

【参考方案3】:

您无法检测浏览器是否关闭。

我想到的最佳选择是检查 http 请求的引用值。

如果引用者为空,则用户直接打开您的网站(通过浏览器地址字段或使用保存的收藏链接等) 如果引用者与您自己的域不同,则用户来自其他站点,例如谷歌。

$recreate_cookie = false;
$my_domain = '://example.com';
$referer = $_SERVER['HTTP_REFERER'];
if ( ! $referer )  
  // Website opened directly/via favorites
  $recreate_cookie = true; 

if ( false === strpos( $referer, $my_domain ) )  
  // User arrived from a link of some other website
  $recreate_cookie = true; 


if ( $recreate_cookie ) 
  // Only name and value are required in your case.
  setcookie( 'style', $style );

但请注意,此方法也不是 100% 可靠的,因为用户可以操纵或禁用 http 引用(例如某些浏览器插件或可能在使用浏览器隐身模式时)


除了难以检测浏览器是否关闭之外,我建议为此使用 PHP 会话。

会话的优势在于您可以在不降低网站速度的情况下存储尽可能多的数据:当您打开网站时,您的所有 cookie 都会发送到服务器,所以如果您有很多数据存储在 cookie 中,然后加载的每个页面来回传输大量数据。另一方面,会话只会将一个 ID 值传输到服务器,服务器会将与该 ID 连接的所有数据存储在服务器上,节省了大量的传输量。

if ( ! session_id() )  session_start(); 

// do the referer check here

if ( $recreate_cookie )  
  $_SESSION['style'] = $style; 
  

也许添加一个不会在 15 分钟内刷新样式的计时器是有意义的 - 所以当用户关闭浏览器并在 15 分钟内再次打开您的页面时,他将拥有与以前相同的样式。

// do the session start and referer check here

if ( $recreate_cookie ) 
  $expires = intval( $_SESSION['style_expire'] );
  if ( $expires > time() )  $recreate_cookie = false; 


if ( $recreate_cookie )  
  $_SESSION['style'] = $style; 

  // Style will not change in the next 15 minutes
  $_SESSION['style_expire'] = time() + 15 * 60; 
  

(所有这些代码都未经测试,所以它可能无法按原样工作,但我想你明白了)

【讨论】:

以上是关于PHP会话cookie在浏览器关闭时过期的主要内容,如果未能解决你的问题,请参考以下文章

cookies不设置过期时间默认是永远不过期吗

过期时间为“会话结束”的 cookie 啥时候过期?

具有expor = 0的setcookie不会在浏览器关闭后失效

如何让 PHP 会话在浏览器关闭或一段时间后过期

将cookie设置为在会话结束时过期?网

Cookie