4
votes

session_destroy() destroys session data but does not unset any of the global variables associated with session or unset the session cookie.

So why should we destroy session?

Can we destroy a session at the end of page each time the session starts in the beginning of that page giving the same functionality without destroying as well?

2
Possibly duplicate of What does Session Destroy Do in PHPJVE
session_destroy simply doesn't do its intended job very well, try this approach.Martin
After using session_destroy(), the session cookie is removed and the session is no longer stored on the server. The values in $_SESSION may still be available, but they will not be on the next page load.Daan

2 Answers

7
votes

session_destroy() will delete the session file (if file storage is used). Otherwise the session file will reside on the server until the garbage collection deletes it. So, if you want to make sure that the stored session data is removed from the server you have to call session_destroy().

Do not call this on every page! Only after the user logs out and you do not need the stored information anymore.

0
votes

Your correct approach should be to run session_destroy, and then reload the page to force the session changing actions (such as cookie deletion) to work and then the session data in PHP reloads and renews upon page reload.

Before running session destroy you should also "manually" clean the session as well so:

<?php
session_start();

if(count)$_SESSION > 0) {
// Or some other more specific cursory check if the session is populated 
    $_SESSION = array("","","",""); 
    session_destroy();
    header("Location: thispage.php");
    exit;
    }

...
Page continues....

Also please reference this answer as to how to remove session cookies on the client browser.