Reputation: 5925
Got it from php.net, but I am not sure is this how everybody destroy all sessions?
// Unset all Sessions
$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time() -42000, '/');
}
session_destroy();
Does the code will destroy all the sessions?? Is it the most common way? how do you guys destroy php sessions?
Oh yeah, btw, what is that session_name()
? All session name? e.g $_SESSION['var1']
, $_SESSION['var2']
, ... ?
I dont need to use unset($_SESSION['var1']);
any more right?
Whats the different between using session_destroy()
and unset($_SESSION[])
?
Upvotes: 15
Views: 38378
Reputation: 1929
To remove all session files from PHP, you can use this function:
<?php
/**
* Hack to destroy all PHP session files
*
* @param string $prefixSessionFile Prefix of the session filename
* @param int|null|false $sessionIdLength Expected Length of the session ID in the session filename. null: Determine automatically. false: do not check
*
* @return int Removed sessions
* @throws Exception
*/
function destroyAllPhpSessionFiles($prefixSessionFile = 'sess_', $sessionIdLength = 26)
{
if (session_status() === PHP_SESSION_DISABLED) {
throw new Exception('Session handling is disabled');
}
if ($sessionIdLength === null) {
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
$sessionIdLength = strlen(session_id());
}
// Allow to remove current session
session_abort();
// Get session dir
if (!$sessionDir = session_save_path()) {
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
// Windows
$sessionDir = sys_get_temp_dir();
// If this script is called from a user (example in cmd), but your server uses the system environment variable (system-wide temp dir):
//$sessionDir = system('echo %windir%') . DIRECTORY_SEPARATOR . 'Temp';
} elseif (is_dir('/var/lib/php5')) {
// Ubuntu or Debian
$sessionDir = '/var/lib/php5';
} elseif (is_dir('/var/lib/php/session')) {
// RHEL or CentOS
$sessionDir = '/var/lib/php/session';
}
if (!$sessionDir || !is_dir($sessionDir)) {
$sessionDir = sys_get_temp_dir();
}
}
// Drop session files
$files = scandir($sessionDir);
$sessionsDeleted = 0;
$prefixLength = strlen($prefixSessionFile);
$filenameLength = $prefixLength + $sessionIdLength;
foreach ($files AS $file) {
if (substr($file, 0, $prefixLength) != $prefixSessionFile) {
// Prefix does not fit
continue;
}
if ($sessionIdLength && strlen($file) != $filenameLength) {
// Filename length does not fit
continue;
}
$path = $sessionDir . DIRECTORY_SEPARATOR . $file;
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
// Windows
exec('DEL ' . $path);
} else {
// Linux / Unix
shell_exec('rm -f ' . $path);
}
if (is_file($path)) {
throw new Exception('Could not delete session file ' . $path);
}
$sessionsDeleted++;
}
return $sessionsDeleted;
}
Upvotes: 0
Reputation: 853
The easiest way is not to delete all sessions at once, but to remember your last login and timestamp of the session reset.
//Start your session
session_start();
//Get your stored timestamp of reset
//(i.e. stored in database)
$timestamp_reset = ...
//Get your stored timestamp of your session
//(i.e. store it in session or database when you log in)
$timestamp_session = ...
//See if the login was before the reset timestamp
if ( $timestamp_reset > $timestamp_session ) {
//Reset you session and go on
session_unset();
}
It will not remove all session files, but will prevent old sessions running. And you do not have to rely on the garbage collector. Didn't find a similar answer here so I had to add this one. Have a nice day.
To your further questions:
Your code will only destroy your single session and is the most common way to i.e. sign out.
session_name will give you the name of the variable, php uses for cookie exchange, you'll not need that most of the time. The code that is used in your example is a very old one, please do not use this.
You do not have to unset every single array item by unset if you use session_destroy or session_unset.
unset($_SESSION) will not work.
Upvotes: 0
Reputation: 2312
You will have to delete the session records.
if session handled by DB - delete the rows.
if session handled by FILES - delete the files.
here you can find full example:
http://mdb-blog.blogspot.co.il/2015/05/php-destroydelete-all-sessions.html
Upvotes: 1
Reputation: 357
If you want to avoid the warning:
Warning: session_destroy(): Trying to destroy uninitialized session in ... on line 18
Don't forget to add session_start();
to the beginning of your code. Other than that the code you provided works as intended.
Upvotes: 0
Reputation: 712
i know this is an old thread...but i just wanted to share :)
i found out that instead of using a temp folder for the session you could save it into a database. so technically, management of sessions is possible.
My Code:
(mostly plaigiarised from http://www.tonymarston.net/php-mysql/session-handler.html#session.handler):
mysql:
CREATE TABLE `php_session` (
`session_id` varchar(32) NOT NULL default '',
`user_id` varchar(16) default NULL,
`date_created` datetime NOT NULL default '0000-00-00 00:00:00',
`last_updated` datetime NOT NULL default '0000-00-00 00:00:00',
`session_data` longtext,
PRIMARY KEY (`session_id`),
KEY `last_updated` (`last_updated`)
)
the session handler (i put it in a separate file called php_session.class.php):
<?php
class php_Session
{
// ****************************************************************************
// This class saves the PHP session data in a database table.
// ****************************************************************************
// ****************************************************************************
// class constructor
// ****************************************************************************
function php_Session ()
{
} // php_Session
// ****************************************************************************
function open ($save_path, $session_name)
// open the session.
{
// do nothing
return TRUE;
} // open
// ****************************************************************************
function close ()
// close the session.
{
if (!empty($this->fieldarray)) {
// perform garbage collection
$result = $this->gc(ini_get('session.gc_maxlifetime'));
// $result = ini_set('session.gc_maxlifetime',0);
return $result;//$result
} // if
return FALSE;
} // close
// ****************************************************************************
function read ($session_id)
// read any data for this session.
{
// $fieldarray = $this->_dml_getData("session_id='" .addslashes($session_id) ."'");
$fieldarray=array();
$data= mysql_query("select * from php_session where session_id='" .addslashes($session_id) ."'")or die(mysql_error());
while($row = mysql_fetch_array($data)) $fieldarray[]=$row;
if (isset($fieldarray[0]['session_data'])) {
$this->fieldarray = $fieldarray[0];
$this->fieldarray['session_data'] = '';
return $fieldarray[0]['session_data'];
} else {
return ''; // return an empty string
} // if
} // read
// ****************************************************************************
function write ($session_id, $session_data)
// write session data to the database.
{
if (!empty($this->fieldarray)) {
if ($this->fieldarray['session_id'] != $session_id) {
// user is starting a new session with previous data
$this->fieldarray = array();
} // if
} // if
if (empty($this->fieldarray)) {
// create new record
$a = $session_id;
$b = date("Y-m-d H:i:s");
$c = date("Y-m-d H:i:s");
$d = addslashes($session_data);
// $this->_dml_insertRecord($array);
mysql_query("insert into php_session (session_id,date_created,last_updated,session_data) values ('$a','$b','$c','$d')");
} else {
// update existing record
if (isset($_SESSION['login_id'])) {
$a = $_SESSION['login_id'];
} // if
$b = date("Y-m-d H:i:s");
$c = addslashes($session_data);
// $this->_dml_updateRecord($array, $this->fieldarray);
mysql_query("update php_session set last_updated='$b',session_data='$c',user_id='$a' where session_id='$session_id'");
$data= mysql_query("select * from php_session where session id='" .addslashes($session_id) ."'");
while($row = mysql_fetch_array($data)) $fieldarray[]=$row;
$this->fieldarray = $fieldarray[0];
} // if
return TRUE;
} // write
// ****************************************************************************
function destroy ($session_id)
// destroy the specified session.
{
$fieldarray['session_id'] = $session_id;
mysql_query("delete from php_session where session_id='$session_id'");
return TRUE;
} // destroy
// ****************************************************************************
function gc ($max_lifetime)
// perform garbage collection.
{
$real_now = date('Y-m-d H:i:s');
$dt1 = strtotime("$real_now -$max_lifetime seconds");
$dt2 = date('Y-m-d H:i:s', $dt1);
// $count = $this->_dml_deleteSelection("last_updated < '$dt2'");
mysql_query("delete from php_session where last_updated < '$dt2'");
$count = mysql_affected_rows();
return TRUE;
} // gc
// ****************************************************************************
function __destruct ()
// ensure session data is written out before classes are destroyed
// (see http://bugs.php.net/bug.php?id=33772 for details)
{
@session_write_close();
} // __destruct
// ****************************************************************************
}
?>
sorry for the messy code there.
To Use
IMPORTANT : put before calling session_start()
require_once 'php_session.class.php';
$session_class = new php_Session;
session_set_save_handler(array(&$session_class, 'open'),
array(&$session_class, 'close'),
array(&$session_class, 'read'),
array(&$session_class, 'write'),
array(&$session_class, 'destroy'),
array(&$session_class, 'gc'));
then call in session_start() and your done!
Since its in mysql, you could see who's online via user id (which is set yourself using $_SESSION), and perform functions like logging them out and stuff (thats what im using it for).
Upvotes: 2
Reputation: 24933
To destroy a single session, you should use the following:-
session_destroy();
Assuming you've used session_start() to previously start/resume a session.
Destroying all sessions really depends on your setup, and how you're handling sessions.
For most PHP installs, the session handling is done via files, so the best way would be to find the folder that keeps all the sessions (usually found from session_save_path()), and delete all the files under that.
I think though, the best way to handle this might be to pre-emptively set a timestamp in each session you create. This means that you can then compare that timestamp to a set point (the time when you want to invalidate all sessions) and invalidate the session if it's before that time. This also means that you can do things like set a specific timeout for a session, etc etc.
Another way might be to change to use Database Stored Sessions - you can find a good tutorial for this here
Upvotes: 2
Reputation: 655219
You should first know what sessions are: You can consider sessions as a data container on the server side that’s associated with a random identifier, the session ID. That session ID needs to be provided by the client so that the server can load the data associated to that session ID (and thus to that session) into the $_SESSION
variable. Everything in that $_SESSION
variable is also called session variables of the current active session.
Now to your questions:
Does the code will destroy all the sessions?? Is it the most common way? how do you guys destroy php sessions??
The provided code just deletes the session data of the current session. The $_SESSION = array();
statement will simply reset the session variable $_SESSION
so that a future access on the session variable $_SESSION
will fail. But the session container itself is not deleted yet. That will be done by calling session_destroy
.
See also Truly destroying a PHP Session?
Oh yeah, btw, what is that session_name()?? All session name? e.g $_SESSION['var1'], $_SESSION['var2']... ?
The session_name is just used to identify the session ID parameter passed in a cookie, the URL’s query or via a POST parameter. PHP’s default value is PHPSESSID
. But you can change it to whatever you want to.
I dont need to use unset($_SESSION['var1']); any more right???
No. The initial $_SESSION = array();
deletes all the session data.
Whats the different between using session_destroy and unset($_SESSION[])??
session_destroy
will delete the whole session container while unset
or resetting the $_SESSION
variable will only delete the session data for the current runtime.
Upvotes: 23
Reputation: 321588
session_name()
is the name that's passed in the cookie / querystring. It's normally PHPSESSID but can be changed.
There's no proper way to destroy all sessions.
As @Marius says, you could try deleting the session files from session_save_path()
but that's a hack at best.
Alternatively you could use session_set_save_handler()
to save your sessions to somewhere you have more control over, such as a database.
Upvotes: 2
Reputation: 58921
This only destroys the current users session, not all the other users session.
Try using the session_save_path() to find out where the session data is being stored, and then delete all the files there.
Upvotes: 12