Search code examples
databasesessioncakephplimitlogout

Is it possible to save additonal data in Sessions Table in CakePHP 3?


I need to do the following tasks in CakePHP 3:

  • Logout users manually
  • Limit the number of sessions to one per user

I'm using database sessions to accomplish that. Is it possible to save additional data in sessions table? If yes, could you give me an example please?


Solution

  • The session database model is a cake model like all the other models, which means you can interact with it, in the same way, by adding new columns to that table and/or deleting sessions if needed. Use the model object to update delete entities in that table (I assume you're talking about cakephp 3.x)

    Limiting the number of sessions to one per user can be tricky as sessions are created even if a user is not logged in. So you will have "user-less" sessions in your database as well.

    Suggested way to tackle this

    • When a user logs in, get the current session ID and find the row in the session table that needs to be updated to include the username

    • At this time you may also want to delete the other rows that have the same user name, effectively destroying all the other sessions for this user.