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

时间:2015-05-29 15:09:07

标签: php wordpress session cookies

我在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只在浏览器关闭时到期?

3 个答案:

答案 0 :(得分:6)

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, '', ...); 

必须工作。

答案 1 :(得分:0)

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

 session.cookie_lifetime = 0 

0 =表示浏览器关闭。

答案 2 :(得分:0)

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

我想到的最佳选择是检查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; 
}  

(所有这些代码都是未经测试的,所以它可能无法正常工作,但我想你明白了这一点)

相关问题