Welcome Guest, Not a member yet? Register   Sign In
Multi Session library
#1

[eluser]jegbagus[/eluser]
Cart library is work really great, but i used to separate login session (use CI session library) with my cart (using cookies).

but now they were placed in the one session that have the same expire time.
the problem come when i need my session library expire earlier than cart library (cart library actually never be expire)

Here i create library that separate life time of your group of session (if you mention my earlier post, i always have a problem with many session life time).

preparation :
- add library in your library folder and named it Multi_Session.php
- extend session library and save it to library folder and named it My_Session.php
- it is better to set your session expire to 0 at your config file.
Code:
$config['sess_expiration']        = 0;


How to Use :

Loading library :
Code:
$this->load->library('Multi_Session');

Set Session Data : You must at least set expire session time
Code:
$newdata = array(
   'name' => 'user',
   'email' => '[email protected]',
   'expire' => 3600
);

$this->multi_session->set_userdata('login',$newdata);

Read Session Data :
Code:
$this->multi_session->user_data('login','name')

Unset Session Data :
Code:
$this->multi_session->unset_userdata('login','name')
or to remove all session data from group:
Code:
$this->multi_session->unset_userdata('login')


Update Session Data :
Code:
$this->multi_session->update_userdata('login','name','anotheruser');


Multi_Session.php
Code:
<?php if(!defined('BASEPATH')) exit("Hack attempt?");

/**
* Crete session that have different life time.
*
* @author Jegbagus
*
* @property CI_Session $session
*/

class Multi_Session {
    var $data = array();
    var $CI;
    var $now;

    /**
     * multi session constructor
     *
     * remove all expire session
     */
    function __construct() {
    // get CI Instance
        $this->CI = & get_instance();

        // load session library
        $this->CI->load->library('session');

        // get all Session data
        $this->data = $this->CI->session->all_userdata();
        $this->now = $this->CI->session->_get_time();

        // itterate every array to find array in array
        foreach($this->data as $var => $value) {

        // check if data is array
            if(is_array($value)) {

            // and check if there is expire value
                if(isset ($value['expire'])) {
                    if($this->is_expire($value['expire'])) {
                        log_message('debug','Is Expire');
                        $this->CI->session->unset_userdata($var);
                    }
                    else {
                        log_message('debug','Not Expire');
                    }
                }
            }

        }

        log_message('debug','Multi Session Initialized');
    }


     /**
      * check if session has expire
      *
      * @param <int> $expire
      * @return <boolean>
      * @access private
      */
    function is_expire($expire) {
        return $this->now - $this->CI->session->get_last_activity() > $expire;
    }

    /**
     * Set user data
     * @example $this->multi_session->set_userdata('login',array('name'=>'user','expire'=>7200));
     *
     * @param <string> $id
     * @param <array> $userdata
     * @return <boolean>
     * @access public
     */
    function set_userdata($id, $userdata) {
        // array must contain expire value and it must be a number
        if(!isset ($userdata['expire']) ) {
            log_message('debug','cannot found expire key');
            return false;
        }

        if(!is_numeric($userdata['expire'])) {
            log_message('debug','expire key must be a number');
            return false;
        }
        // save to session database
        $this->CI->session->set_userdata(array ($id =>  $userdata ));

        return true;
    }

    /**
     * get session data
     *
     * @param <string> $id
     * @param <string> $item
     * @return &lt;object&gt; can be boolean, or string
     * @access public
     */
    function user_data($id, $item) {
        $var = $this->CI->session->userdata($id);
        return (! isset($var[$item]) ) ? FALSE : $var[$item] ;
    }

    /**
     * get all session data
     *
     * @param <sting> $id
     * @return &lt;object&gt; can be boolean, or a string
     * @access public
     */
    function all_userdata($id) {
        $var = $this->CI->session->userdata($id);
        return (! isset($var)) ? FALSE : $var ;
    }

    /**
     * unset session data
     * @example $this->multi_session->set_userdata('login') or <br/>
     *          $this->multi_session->set_userdata('login','name')
     *
     * @param <string> $id
     * @param <string> $item
     * @return <boolean>
     * @access public
     */
    function unset_userdata($id, $item = null) {
        if(isset($id) && !is_null($item)) {
            $data = $this->all_userdata($id);
            unset($data[$item]);
            $this->set_userdata($id, $data);
            return true;
        }

        if(isset($id)) {
            unset($this->data);
            $this->CI->session->unset_userdata($id);
            return true;
        }
    }

    /**
     * update one of session data value
     * @example $this->multi_session->update_userdata('login','name','anotheruser')
     *
     * @param <string> $id
     * @param <string> $item
     * @param <void>
     * @access public
     */
    function update_userdata($id, $item, $value) {

        $data = $this->all_userdata($id);

        if(is_array($data)) {
            $this->unset_userdata($id);
            $data[$item] = $value;
            $this->set_userdata($id, $data);
        }

    }
}
#2

[eluser]jegbagus[/eluser]
My_Session.php

Code:
&lt;?php if(!defined('BASEPATH')) exit("Hack attempt?");

/**
* Description
*
* @author Jegbagus
*
* @property
*/

class My_Session extends CI_Session {

    var $last_activity;

    function __construct() {
        parent::__construct();
    }

    function get_last_activity(){
        return $this->last_activity;
    }

    // override function
    function sess_read() {
    // Fetch the cookie
        $session = $this->CI->input->cookie($this->sess_cookie_name);

        // No cookie?  Goodbye cruel world!...
        if ($session === FALSE) {
            log_message('debug', 'A session cookie was not found.');
            return FALSE;
        }

        // Decrypt the cookie data
        if ($this->sess_encrypt_cookie == TRUE) {
            $session = $this->CI->encrypt->decode($session);
        }
        else {
        // encryption was not used, so we need to check the md5 hash
            $hash     = substr($session, strlen($session)-32); // get last 32 chars
            $session = substr($session, 0, strlen($session)-32);

            // Does the md5 hash match?  This is to prevent manipulation of session data in userspace
            if ($hash !==  md5($session.$this->encryption_key)) {
                log_message('error', 'The session cookie data did not match what was expected. This could be a possible hacking attempt.');
                $this->sess_destroy();
                return FALSE;
            }
        }

        // Unserialize the session array
        $session = $this->_unserialize($session);
        
        // get last activity
        $this->last_activity = $session['last_activity'];

        // Is the session data we unserialized an array with the correct format?
        if ( ! is_array($session) OR ! isset($session['session_id']) OR ! isset($session['ip_address']) OR ! isset($session['user_agent']) OR ! isset($session['last_activity'])) {
            $this->sess_destroy();
            return FALSE;
        }

        // Is the session current?
        if (($session['last_activity'] + $this->sess_expiration) < $this->now) {
            $this->sess_destroy();
            return FALSE;
        }

        // Does the IP Match?
        if ($this->sess_match_ip == TRUE AND $session['ip_address'] != $this->CI->input->ip_address()) {
            $this->sess_destroy();
            return FALSE;
        }

        // Does the User Agent Match?
        if ($this->sess_match_useragent == TRUE AND trim($session['user_agent']) != trim(substr($this->CI->input->user_agent(), 0, 50))) {
            $this->sess_destroy();
            return FALSE;
        }

        // Is there a corresponding session in the DB?
        if ($this->sess_use_database === TRUE) {
            $this->CI->db->where('session_id', $session['session_id']);

            if ($this->sess_match_ip == TRUE) {
                $this->CI->db->where('ip_address', $session['ip_address']);
            }

            if ($this->sess_match_useragent == TRUE) {
                $this->CI->db->where('user_agent', $session['user_agent']);
            }

            $query = $this->CI->db->get($this->sess_table_name);

            // No result?  Kill it!
            if ($query->num_rows() == 0) {
                $this->sess_destroy();
                return FALSE;
            }

            // Is there custom data?  If so, add it to the main session array
            $row = $query->row();
            if (isset($row->user_data) AND $row->user_data != '') {
                $custom_data = $this->_unserialize($row->user_data);

                if (is_array($custom_data)) {
                    foreach ($custom_data as $key => $val) {
                        $session[$key] = $val;
                    }
                }
            }
        }

        // Session is valid!
        $this->userdata = $session;
        unset($session);

        return TRUE;
    }

}
#3

[eluser]BrianDHall[/eluser]
Wow, this is actually a very cool idea. Thanks for contributing your code!
#4

[eluser]jegbagus[/eluser]
you are welcome Brian Smile
#5

[eluser]NikhilSukul[/eluser]
Will it also handles session per tab setup if you want in FF?
#6

[eluser]bfj[/eluser]
Actually, you don't need to create an additional library for multiple session (session cookie) management. You can use CI's built in session class by just loading multiple session object instances with different names to create separate sessions and using them, where any of those objects are needed. Something like this:
Code:
// Create session1
$config_session1 = array(
    'sess_cookie_name' => 'session1',
    'sess_expiration' => 3600
);
$this->load->library('session', $config_session1, 'session1');
// Do something with data of session1
$this->session1->set_userdata('sess1_data', $sess1_data);
$sess1_data = $this->session1->userdata('sess1_data');

// Create session2
$config_session2 = array(
    'sess_cookie_name' => 'session2',
    'sess_expiration' => 7200
);
$this->load->library('session', $config_session2, 'session2');
// Do something with session2
$this->session2->set_userdata('sess2_data', $sess2_data);
$sess2_data = $this->session2->userdata('sess2_data');
It creates two cookies with appropriate configurations:
- session1 - expires in 1 hour;
- session2 - expires in 2 hours.
#7

[eluser]SlasHo[/eluser]
Hi, is there any way to use, Session.php from 1.7.3 in a CI 1.5.4 ??

I need to use the example above in 1.5.4 (multiple cookies)

any ideas??




Theme © iAndrew 2016 - Forum software by © MyBB