`
only_java
  • 浏览: 109895 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

关于php中session和cookie

    博客分类:
  • php
阅读更多

 

 

创建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();
?> 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics