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

不打扰是莪最后的温柔 提交于 2019-11-26 05:57:29

问题


From the php.net documentation:

session_destroy — Destroys all data registered to a session

session_unset — Free all session variables

My three part question is:

The two functions seem very similar.
What is really the difference between the two?

Both seem to delete all variables registered to a session. Does any of them actually destroy the session itself? If not, how do you accomplish this (destroy the session itself).

Is it correct that neither of the two functions deletes the session cookie at the client?


回答1:


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

$_SESSION = array();

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.




回答2:


session_destroy(); is deleting the whole session.

session_unset(); deletes only the variables from session - session still exists. Only data is truncated.




回答3:


session_unset();

Just clear all data of all session variable.


session_destroy();

Remove all session.


Example:
session_start();
session_destroy();     
$a = "1234";
$_SESSION[a] = $a;

$_SESSION[a] is NULL.


session_start();
session_unset();     
$a = "1234";
$_SESSION[a] = $a;

$_SESSION[a] is 1234.


So, I will use:

session_start();
session_destroy();   
session_start();  
$a = "1234";
$_SESSION[a] = $a;



回答4:


session_unset() will clear the $_SESSION variable (as in array()), but it won't touch the session file. But when the script ends; the state of the $_SESSION will be written to the file. Then it will clear the file but won't delete it. When you use session_destroy() it won't touch $_SESSION (Use var_dump($_SESSION) after session_destroy()), but will delete the session file, so when script exits there won't be a file to write the state of the $_SESSION.




回答5:


session_destroy() will delete the session after moving the page and session_unset() will delete session when the code is run.




回答6:


I tried to use session_unset($_SESSION['session_name']) thinking it will only unset specific or individual/single session name. But using session_unset($_SESSION['session_name']) will only unset all session name. The right code to use is only unset($_SESSION['session_name']) if you want to unset a single session name.




回答7:


I think session_destroy() and session_unset() should be used at the same time to make sure that session data is surely deleted.



来源:https://stackoverflow.com/questions/4303311/what-is-the-difference-between-session-unset-and-session-destroy-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!