Viewed   50 times

I have heard mixed responses on this topic, so what is a sure fire way to destroy a PHP session?

session_start();
if(isset($_SESSION['foo'])) {
   unset($_SESSION['foo'];
   ...
}
session_destroy();

In the most simple of cases, would this sufficient to truly terminate the session between the user and the server?

 Answers

5

To destroy a session you should take the following steps:

  • delete the session data
  • invalidate the session ID

To do this, I’d use this:

session_start();
// resets the session data for the rest of the runtime
$_SESSION = array();
// sends as Set-Cookie to invalidate the session cookie
if (isset($_COOKIE[session_name()])) { 
    $params = session_get_cookie_params();
    setcookie(session_name(), '', 1, $params['path'], $params['domain'], $params['secure'], isset($params['httponly']));
}
session_destroy();

And to be sure that the session ID is invalid, you should only allow session IDs that were being initiated by your script. So set a flag and check if it is set:

session_start();
if (!isset($_SESSION['CREATED'])) {
    // invalidate old session data and ID
    session_regenerate_id(true);
    $_SESSION['CREATED'] = time();
}

Additionally, you can use this timestamp to swap the session ID periodically to reduce its lifetime:

if (time() - $_SESSION['CREATED'] > ini_get('session.gc_maxlifetime')) {
    session_regenerate_id(true);
    $_SESSION['CREATED'] = time();
}
Thursday, August 18, 2022
4

You know that you've got to write session_start() before you use the $_SESSION variable in any request, right? It looks like you haven't put it in index.php anywhere.

Friday, December 16, 2022
4

No it is not a valid code. It will destroy the session at the time of loading the php page.

For destroying session on click you should write

<a href="logout.php" >Logout</a>

in logout.php

session_destroy();
Saturday, September 17, 2022
 
1

CodeIgniter has a session class that does not utilize native PHP sessions.

Friday, August 5, 2022
 
gremash
 
5

Instead of setting the time in ini to a fixed length, remind that session timeout is reset on reload. So create some ajax code that does a request every 5 minutes or so to a file (image or smth). This way the timer is reset every 5 minutes and users can spend a day filling out your forms.

Saturday, November 5, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :