简体   繁体   中英

How to properly delete a PHP session?

I previously used these three lines to delete a session:

session_start();
session_regenerate_id();
session_destroy();

Does session_destroy() close the session, or do I have to close it manually?

session_start();
session_regenerate_id();
$_SESSION = array();
session_write_close();

session_destroy delete the session's data in the media (file, database, etc) where is stored, but doesn't delete the $_SESSION array or the cookies, you have to do it manually, that includes the PHPSESSID cookie.

I normally delete the sessions with something like this:

foreach($_SESSION as $key => $val)
    unset($_SESSION[$key]);
foreach($_COOKIE as $key => $val)
    setcookie($key, '', 1);
session_destroy();


BTW when you call session_regenerate_id() the session's file is copied to the new file but the old one isn't deleted, if you want to delete the old data session's file (probably you want) you must specify it with session_regenerate_id(TRUE) .

If you are destroying the session then there isn't really a need to session_write_close(), as in the manual it does the following:

Session data is usually stored after your script terminated without the need to call session_write_close(), but as session data is locked to prevent concurrent writes only one script may operate on a session at any time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM