How to store sessions in Database

Discussion in 'PHP' started by clobberx, Jun 10, 2008.

  1. #1
    Help me to store the sessions directly into database
     
    clobberx, Jun 10, 2008 IP
  2. softvision

    softvision Peon

    Messages:
    146
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Can you explain what do you mean?
     
    softvision, Jun 11, 2008 IP
  3. abs0lut01

    abs0lut01 Peon

    Messages:
    5
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    INSERT INTO table_name (column1, column2,...)
    VALUES (value1, value2,....)
     
    abs0lut01, Jun 11, 2008 IP
  4. clobberx

    clobberx Active Member

    Messages:
    73
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    61
    #4
    i mean this

    session_set_save_handler
     
    clobberx, Jun 11, 2008 IP
  5. sky22

    sky22 Guest

    Messages:
    59
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Hello,

    You need to make a set of functions for the handler to use:

    "open" - Connect to DB
    "close" - Disconnect from DB
    "read" - Select session from DB
    "write" - Insert/Update seddion from DB
    "destroy" - Delete session from DB
    "gc" - Remove old sessions from DB

    Then give all the functions to the set_handler function so they will be used.

    The easiest way is to see one that's already done. The PHP manual comments has some good example of what you want to do like this one:

    
    Initiated from maria at junkies dot jp comment.
    <?php
    /**
     * PHP session handling with MySQL-DB
     *
     * Created on 12.03.2008
     * @license    http://www.opensource.org/licenses/cpl.php Common Public License 1.0
     */
    
    class Session
    {
        /**
         * a database connection resource
         * @var resource
         */
        private static $_sess_db;
    
        /**
         * Open the session
         * @return bool
         */
        public static function open() {
           
            if (self::$_sess_db = mysql_connect('localhost',
                                                'root',
                                                '')) {
                return mysql_select_db('my_application', self::$_sess_db);
            }
            return false;
        }
    
        /**
         * Close the session
         * @return bool
         */
        public static function close() {
            return mysql_close(self::$_sess_db);
        }
    
        /**
         * Read the session
         * @param int session id
         * @return string string of the sessoin
         */
        public static function read($id) {
            $id = mysql_real_escape_string($id);
            $sql = sprintf("SELECT `session_data` FROM `sessions` " .
                           "WHERE `session` = '%s'", $id);
            if ($result = mysql_query($sql, self::$_sess_db)) {
                if (mysql_num_rows($result)) {
                    $record = mysql_fetch_assoc($result);
                    return $record['session_data'];
                }
            }
            return '';
        }
    
        /**
         * Write the session
         * @param int session id
         * @param string data of the session
         */
        public static function write($id, $data) {
            $sql = sprintf("REPLACE INTO `sessions` VALUES('%s', '%s', '%s')",
                           mysql_real_escape_string($id),
                           mysql_real_escape_string(time()),
                           mysql_real_escape_string($data)
                           );
            return mysql_query($sql, self::$_sess_db);
        }
    
        /**
         * Destoroy the session
         * @param int session id
         * @return bool
         */
        public static function destroy($id) {
            $sql = sprintf("DELETE FROM `sessions` WHERE `session` = '%s'", $id);
            return mysql_query($sql, self::$_sess_db);
        }
    
        /**
         * Garbage Collector
         * @param int life time (sec.)
         * @return bool
         * @see session.gc_divisor      100
         * @see session.gc_maxlifetime 1440
         * @see session.gc_probability    1
         * @usage execution rate 1/100
         *        (session.gc_probability/session.gc_divisor)
         */
        public static function gc($max) {
            $sql = sprintf("DELETE FROM `sessions` WHERE `session_expires` < '%s'",
                           mysql_real_escape_string(time() - $max));
            return mysql_query($sql, self::$_sess_db);
        }
    }
    
    //ini_set('session.gc_probability', 50);
    ini_set('session.save_handler', 'user');
    
    session_set_save_handler(array('Session', 'open'),
                             array('Session', 'close'),
                             array('Session', 'read'),
                             array('Session', 'write'),
                             array('Session', 'destroy'),
                             array('Session', 'gc')
                             );
    
    if (session_id() == "") session_start();
    //session_regenerate_id(false); //also works fine
    if (isset($_SESSION['counter'])) {
        $_SESSION['counter']++;
    } else {
        $_SESSION['counter'] = 1;
    }
    echo '<br/>SessionID: '. session_id() .'<br/>Counter: '. $_SESSION['counter'];
    
    ?>
    
    And don't miss the table dump. ^^
    
    CREATE TABLE IF NOT EXISTS `sessions` (
      `session` varchar(255) character set utf8 collate utf8_bin NOT NULL,
      `session_expires` int(10) unsigned NOT NULL default '0',
      `session_data` text collate utf8_unicode_ci,
      PRIMARY KEY  (`session`)
    ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    PHP:
    Which does exactly what you're trying to do.

    Sky22
     
    sky22, Jun 11, 2008 IP
  6. joffer

    joffer Peon

    Messages:
    85
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #6
    The default is session.save_handler (files | mm | user | memcache)
    If you want to store them in database , better use memcache and there are enough php functions to use it from there
     
    joffer, Jun 11, 2008 IP
  7. clobberx

    clobberx Active Member

    Messages:
    73
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    61
    #7
    Nice post thanks
     
    clobberx, Jun 11, 2008 IP