创建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();
?>
本文介绍PHP中Cookie的基本操作,包括创建、设置路径、指定失效时间等,并解释了Cookie如何随HTTP包发送。此外还详细说明了如何销毁Cookie及与Session结合使用的注意事项。
1957

被折叠的 条评论
为什么被折叠?



