5

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?

Hamza Zafeer
  • 2,360
  • 13
  • 30
  • 42
user6181297
  • 113
  • 2
  • 11
  • 1
    Possibly duplicate of [What does Session Destroy Do in PHP](http://stackoverflow.com/questions/18549211/what-does-session-destroy-do-in-php) – JVE Apr 13 '16 at 14:32
  • 1
    `session_destroy` simply doesn't do its intended job very well, [try this approach](http://stackoverflow.com/questions/3948230/best-way-to-completely-destroy-a-session-even-if-the-browser-is-not-closed). – Martin Apr 13 '16 at 14:32
  • 1
    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 Apr 13 '16 at 14:32

2 Answers2

7

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.

Markus Müller
  • 2,611
  • 1
  • 17
  • 25
  • Is it possible to hack the data from session file? Even if we don't delete session_destroy is our data safe by just unsetting session variables? – user6181297 Apr 13 '16 at 14:59
0

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.

Community
  • 1
  • 1
Martin
  • 22,212
  • 11
  • 70
  • 132