ExpressionEngine CMS
Open, Free, Amazing

Thread

This is an archived forum and the content is probably no longer relevant, but is provided here for posterity.

The active forums are here.

NGSession: a combination of CI’s Session in 1.6 and DBSession

February 02, 2008 12:14pm

Subscribe [14]
  • #1 / Feb 02, 2008 12:14pm

    WolfgangA

    46 posts

    Hello,

    started as a feature request for the new session lib in 1.6 to support storage of userdata and flashdata optional in a database, i have released NGSession bc the current session lib in CI v1.6 still stores any userdata or flash variables in the cookie.

    NGSession can be used transparently using cookies or the database. When using a database, only the session_id is stored in the cookie.


    Overview
    - NGSession is based on a combination of Codeignitors Session.php in version 1.6 and DBSession.
    - Fully compatible with Codeignitors Session.php in version 1.54 and 1.6 and DBSession.
    - Designed as drop-in replacement for CI Session and/or DBSession.
    - Any config option like encryption and any functionallity like flash session variables are fully supported.
    - When using a database, only the session_id is stored in a cookie. Any other data is stored in the database.
    - When using without a database, all data is stored in a cookie.
    - Both modi work fully tansparent.

    More details can be found in the wiki: NGSession

    The lib should work with CI v1.54 and v1.60.

    Any feedback is appreciated.

    Wolfgang

    P.S. Thank you to the CI / EE Team for providing such a great framework.

  • #2 / Feb 02, 2008 2:50pm

    Alex007

    49 posts

    This looks interesting, you should post it in the “Ignited Code” forum.

    Also, what are the advantages of your library over the DB_Session library ?

  • #3 / Feb 02, 2008 3:58pm

    sikkle

    325 posts

    i think this is the fact, that you can use it AS cookie session AND database session.

    keep me posted with test and bug, i’ll do some test on my side also.

  • #4 / Feb 03, 2008 7:29am

    WolfgangA

    46 posts

    This looks interesting, you should post it in the “Ignited Code” forum.

    I appologize, you are right.

    If an Admin is reading this, i kindly ask to move this thread into the correct forum.

    Also, what are the advantages of your library over the DB_Session library ?

    As sikkle stated: The lib can handle transparently sessions using cookies AND database without changing any code. So you can use one lib regardless wether you want sessions in database or not.
    Give it a try: start using cookies and then change the config to use database.
    If you had a valid cookie session, a new database session will start and thats it.
    (Since it is a drop in replacement you can simply replace the CI session lib, given you have added the required database field ‘session-data’ as you would for DB Session)

    Pls let me know if you find any bugs. I use it in my current project (using JS EXT, CI 1.6) and it works flawless for me.

    Using NGAuth (not released so far) i also keep the user_groups (memberships/roles of the logged-in user like admin, manager, user etc.) in the session data. That is something i would not want, if the session data were hold in a cookie.

  • #5 / Feb 03, 2008 7:52am

    murphy2006

    69 posts

    Hello,

    I am note sure how to “use” the custom session data saved in the DB.
    What I am looking for is a way to tell if a user is logged in or not.
    What I tried before was to simply add a new field (user) into the table
    and then create a query checking for the username in the sessions table but this
    I was not able to do with the original CI 1.6 session library.

    From what I can see now, using the NGSession, the custom data is saved to the DB which is good, but how do I “extract” it to get the functionality that I was looking for (see above).

    Saved data.

    a:4:{s:2:"id";s:1:"1";s:8:"username";s:6:"hoorl";s:5:"email";s:17:"[email protected]";s:9:"logged_in";b:1;}

    Kind Regards,
    Daniel

  • #6 / Feb 03, 2008 8:04am

    WolfgangA

    46 posts

    You do not have to deal with the database - just get/set sessiondata as you would using CI’s session.
    As i said before: The lib works transparent for cookies and database storage.

    But here a simple example:

    // setting userdata - can be a string, an array…
    //
    // setter - $mydata is an array
    $this->session->set_userdata('user_memberships', $my_data);
    // getter $ret is an array
    $ret = $this->session->userdata('user_memberships')
    //
    // same for string / integer
    //
    $this->session->set_userdata('user_id', $user_id);
    $user_id = $this->session->userdata('user_id');

    This works when using cookies and when using database.

    Really the point is to serialize all userdata (and flashdata) so they can be stored in _one_ database field. This allows to save any user/flashdata without actually having to modify the table structure.

    The serialization itself works similar for using cookies and for database.

  • #7 / Feb 03, 2008 8:26am

    WolfgangA

    46 posts

    To help you, here an example of my login procedure.
    The code won’t work by copy / paste but should give you the idea. You will see, that i use the session API rather than direct access to the session table.
    Note: The db syntax matches the new CI 1.6 activerecord implementation (so won’t work on CI 1.5x)

    /**
         * Validate login using credentials (typically email/password or username/password)
         * On succuess it sets the user_id field in the session userdata and returns the user object
         *
         * @access    public
         * @param    associative array example ('email'=>$email, 'password'=>dohash($password))
         * @return    mixed boolean:false or object with user record
         */
        function login($where = array())
        {
            $query = $this->db->get_where($this->table_user, $where, 1, 0);
    
            if ($query->num_rows != 1) return FALSE;
    
            $row = $query->row();
            $this->session->set_userdata('user_id', $row->id);
    
            return $row;
        }
    
        /**
         * Get user information of current logged in user or a specific user by id
         *
         * @access    public
         * @param    int user_id, default = current session user_id
         * @return    mixed boolean:false or object with user record
         */
        function get_user($id = FALSE)
        {
            if ($id === FALSE)
            {
                if (($id = $this->session->userdata('user_id')) === FALSE)
                {
                    return FALSE;
                }
            }
    
            $where = array(($this->table_user .'.' .$this->field_user_id) =>$id);
            $query = $this->db->get_where($this->table_user, $where, 1, 0);
    
            return ($query->num_rows() == 1) ? $query->row() : FALSE;
        }
    
    
         /**
          * Logout current user
          *
          * No parameter. Logout is done by destroying the current user session.
          *
          *
          * @access    public
          * @return    void
          */
         function logout()
         {
             $this->session->sess_destroy();
         }
  • #8 / Feb 07, 2008 4:22pm

    sirjack

    2 posts

    Hello.

    I get the database error when i try to load the NGSsession library:

    An Error Was Encountered

    Error Number:

    ERROR: syntax error at or near “)” at character 29

    SELECT * FROM (“ci_sessions”) WHERE “session_id” = ‘1d4860f4de1d6656fd6cc8227ca40b77’ AND “ip_address” = ‘xxx.xxx.xxx.xxx’ AND “user_agent” = ‘Mozilla/5.0 (X11; U; Linux i686; PL; rv:1.7.12) Ge’


    I use postgres database. My ci_sessions table looks like that:

    ci_sessions (
      session_id character varying(40) DEFAULT 0 NOT NULL primary key,
      ip_address character varying(16) DEFAULT 0 NOT NULL,
      user_agent character varying(50) NOT NULL,
      last_activity integer DEFAULT 0 NOT NULL,
      session_data text DEFAULT ‘’::text NOT NULL
    );

    My config.php:

    $config[‘sess_cookie_name’]      = ‘ci_session’;
    $config[‘sess_expiration’]      = 7200;
    $config[‘sess_encrypt_cookie’]  = FALSE;
    $config[‘sess_use_database’]  = TRUE;
    $config[‘sess_table_name’]      = ‘ci_sessions’;
    $config[‘sess_match_ip’]      = TRUE;
    $config[‘sess_match_useragent’]  = TRUE;
    $config[‘sess_time_to_update’]    = 300;

    And my controller:

    class Main extends Controller {

    function __construct()
    {
    parent::Controller();
    $this->load->library('session');
    }
    }

    Is there a problem with database library (sth with postgres)? Or am I doing sth wrong?
    I’d appreciate any help…


    edit: i’ve found a solution… -> http://ellislab.com/forums/viewthread/70389/ 😊

  • #9 / Feb 08, 2008 11:14am

    WolfgangA

    46 posts

    Thx for posting the link to the solution to fix the postgre AR driver.

    Does the lib work for you?

  • #10 / Feb 09, 2008 8:56am

    sirjack

    2 posts

    Works great:)
    Thanks for the lib.

  • #11 / Feb 11, 2008 4:52pm

    doors

    39 posts

    This is my big concern about these session libraries.

    Can I store an object in a session and can this object be written to the database?

  • #12 / Feb 12, 2008 5:30am

    WolfgangA

    46 posts

    ...
    Can I store an object in a session and can this object be written to the database?

    Yes, it does store objects(data), arrays, strings, etc. and you can decide wether to use a cookie or a database. Is this what you mean?

  • #13 / Feb 12, 2008 9:10am

    doors

    39 posts

    Yes thanks. I went home and implemented it and it’s working alright so far.

  • #14 / Feb 13, 2008 9:20am

    doors

    39 posts

    The NG Session is giving some problems now. I have some objects I am storing in a session.

    I am loading them in one by one and at a certain number I get a huge error message. I really mean huge. Here is a part of it:

    An Error Was Encountered

    Error Number: 2006

    MySQL server has gone away

    UPDATE sessions_ci SET ip_address = '127.0.0.1', user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv', last_activity = 1202917629, session_data = 'a:5:{s:8:\"store_id\";s:1:\"1\";s:4:\"cart\";O:12:\"ShoppingCart\":5:{s:16:\"ShoppingCartCI\";O:7:\"Welcome\":17:{s:15:\"_ci_scaffolding\";b:0;s:15:\"_ci_scaff_table\";b:0;s:6:\"config\";O:9:\"CI_Config\":2:{s:6:\"config\";a:37:{s:11:\"web_address\";s:14:

    The above line is about 0.1% of what’s there and then at the end of the error message the following prints:

    simplified\";}s:32:\"StoreLanguagecatalog_languages\";a:1:{s:2:\"en\";a:4:{s:2:\"id\";s:1:\"1\";s:4:\"name\";s:7:\"english\";s:5:\"image\";s:11:\"english.gif\";s:9:\"directory\";s:7:\"english\";}}s:32:\"StoreLanguagebrowser_languages\";a:2:{i:0;s:5:\"en-us\";i:1;s:8:\"en;q=0.5\";}s:23:\"StoreLanguagelanguage\";a:4:{s:2:\"id\";s:1:\"1\";s:4:\"name\";s:7:\"english\";s:5:\"image\";s:11:\"english.gif\";s:9:\"directory\";s:7:\"english\";}}s:13:\"recenthistory\";r:196;}s:22:\"ShoppingCartcontents\";a:0:{}s:19:\"ShoppingCarttotal\";i:0;s:20:\"ShoppingCartweight\";i:0;s:26:\"ShoppingCartcontent_type\";b:0;}s:8:\"language\";s:7:\"english\";s:12:\"languages_id\";s:1:\"1\";s:19:\"your_recent_history\";r:196;}' WHERE session_id = '353868fd9eec8915a3d5723d3f9fa66e'

    What is causing this and how can it be fixed.


    I am using now Code Igniter 1.6, Database and Session auto loaded, I am using database to store sessions.

    I was working with Code Igniter 1.5.4 and get the same error and updated to 1.6 last night. I need some help with this.

  • #15 / Feb 14, 2008 2:38pm

    WolfgangA

    46 posts

    I suspect that the serialization of the objects fails. The way serialization is done does not differ from the orginal Session lib, and is the same for db and cookie use.

    Another option would be that the data you are ging to store exceeds the field size of the database. (i do not think that it is the case though)

    So what estimated size of data are you going to store?
    If you use less than 4k, does it work with a cookie?
    Can you write the serialized string into a file and get the filesize and maybe judge if it looks valid? (Maybe you can reread it and deserialize it to see wether it is valid)

.(JavaScript must be enabled to view this email address)

ExpressionEngine News!

#eecms, #events, #releases