关于php中session和cookie

 

 

创建cookie:

1.如果不指明cookie路径php将创建的cookie保存在当前上下文的路径中,比如我在/a/test.php中创建一个cookie,那么Php将在/a目录下生成一个cookie文件,而只有在/a目录下的文件才能访问此cookie

2.一般做法是将路径设为‘/’,这样创建的cookie将在整个域名下都有效。

引用手册上一段:

 

If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in. 

  

 

 

 

3.如果不指明cookie失效时间的话,cookie将在关闭浏览器后失效

 

 

If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes). 

 

 

4.cookie生成后是伴随在http包中发布出来,所以在生成cookie后不能立马获得cookie值,只能通过下次请求获得!因为那时cookie已经夹在http包中。

 

销毁cookie:

 

很多情况下,我们会将cookie和session结合使用。所以必定会牵涉到cookie和session的销毁问题。这就牵涉到先销毁谁的问题,访问网站的来客会被分配一个唯一的标识符-sessionid关联用户创建的cookie,所以得先销毁cookie再销毁session

 

session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. 

In order to kill the session altogether, like to log the user out, the session id must also be unset. If a cookie is used to propagate the session id (default behavior), then the session cookie must be deleted. setcookie() may be used for that. 

 

<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();

// Unset all of the session variables.
$_SESSION = array();

// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (isset($_COOKIE[session_name()])) {
    setcookie(session_name(), '', time()-42000, '/');
}

// Finally, destroy the session.
session_destroy();
?> 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值