session_unset() && session_destroy()

What is the difference between session_unset() and session_destroy() in PHP?




session_unset — Free all session variables

void session_unset ( void )The session_unset() function frees all session variables currently registered.


If $_SESSION (or $HTTP_SESSION_VARS for PHP 4.0.6 or less) is used, use unset() to unregister a session variable, i.e.unset ($_SESSION[‘varname’]);.


Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal.


session_destroy — Destroys all data registered to a session

bool session_destroy ( void )

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. To use the session variables again, session_start() has to be called.

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.



One Explanation:

session_unset just clears the $_SESSION variable. It’s equivalent to doing:

So this does only affect the local $_SESSION variable instance but not the session data in the session storage.

In contrast to that, session_destroy destroys the session data that is stored in the session storage (e.g. the session file in the file system).

Everything else remains unchanged.

Another Explanation:

–> Just clear all data of all session variable.

–> Remove all session


–> $_SESSION[a] is NULL

–> $_SESSION[a] is “1234”

So, I will use:



使用Memcached服务器保存用户的登录信息时,每个用户都有一个sessionID来标识。memcached 中是以key/value  键值对来存储信息的,key的值就是sessionID, value的值就是该用户的session中的信息。

当使用session_unset()时,只是清除了memcached 中指定 key/value 键值对中的value(也就是说该用户的所有session中的信息都没了),但key还存在(也就是说sessionID 还在)。这就相当于该用户没有关闭浏览器(默认浏览器关闭时,相关的sessionID会被清理),即还处于“login”状态,只是session信息没了。

当使用session_destroy()时,相当于用户关闭了浏览器,sessionID没了,之后,没法从session中读写该用户的数据了,若想重新使用session,需再次开启session,即session_start() (此时的session_start() 相当于用户第一次打开该网站,会生成一个新的sessionID,与之前的旧的sessionID不再有关系,顾之前的session信息再也取不到了!除非,,在session_start()之前使用session_id($param)  ,其中$param是之前的旧的sessionID,这样,即使再次开启session_start(),使用的还是之前的sessionID,可以根据该sessionID找回之前存在该sessionID中的value信息)。

使用文件系统存储sessionID 信息的情况好像和使用memcached存储一样(我没试过)。