Is this a proper way to destroy all session data in php?

后端 未结 9 477
耶瑟儿~
耶瑟儿~ 2020-11-27 18:21

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_nam         


        
相关标签:
9条回答
  • 2020-11-27 18:53

    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.

    0 讨论(0)
  • 2020-11-27 18:54

    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).

    0 讨论(0)
  • 2020-11-27 18:55

    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.

    0 讨论(0)
提交回复
热议问题