Yusaf Khaliq
Yusaf Khaliq

Reputation: 3393

Storing data into session and storing to database upon "major" action

I know there are hundreds of these questions but what I am asking however is slightly different.

When the user logs in I would like to get all their data from each table in a database and store it in a session variable (obviously not sensative data such as encrypted password/salts etc basically data that would be useless or have no value to a hacker!!), and whilst the user uses the website the relevant data stored in the session will be used as opposed to accessing the database everytime. Moreover when the data is changed or added this will be written or added to the session file, and upon a major action such as "saving" or "loggin out" the new/changed data will be written to the database.

The reason I wish to do this is simply for efficieny, I want my application to not only be fast but less resource consuming. I am no expert on either which may explain why my idea makes no differnece or is more resource intensive.

If there is an alternative to my solution please let me know or if there is something to improve on my solution I will be glad to hear it.

Thank you. My application is using PHP and mysql.

Upvotes: 11

Views: 3595

Answers (6)

Sachin9
Sachin9

Reputation: 150

I know this sounds stupid but .... If ur data is not sensitive the best way to make it accessible faster is to store it in hidden variables inside the forms itself. You can save comma separated or values in an array.

Upvotes: -1

zzlalani
zzlalani

Reputation: 24374

You can also go for in HTML5, check The Guide and THE PAST, PRESENT & FUTURE OF LOCAL STORAGE FOR WEB APPLICATIONS

Local Storage in HTML5 actually uses your browsers database that works as cookies but it stores data permanently to your browser

  1. unless someone by force remove the data from the browser finding the data files
  2. Or if someone remove/uninstall browser completely,
  3. or if someone uses the application in private/incognito mode of the browser,

What you need to do

  1. Copy the schema for required tables and for required columns and update data at a regular interval
  2. you dont have to worry about user's state, you only have to update the complete data from the localStorage to mysql Server (and from the mysql server to localStorage if required) every time user backs to your application and keep updating the data at regular interval

Now this is turning out to be more of localStorage but I think this is one of the best solution available for me.

Upvotes: 4

Sharky
Sharky

Reputation: 6284

I also use what the OP described to avoid calls to db. For example, when a user logs-in, i have a "welcome-tip" on their control panel like

Welcome, <USERS NAME HERE>

If i stored only his user_id on $_SESSION then in every pageview i would have to retrieve his information from the database just to have his name available, like SELECT user_name FROM users WHERE user_id = $_SESSION['user']['user_id'] So to avoid this, i store some of his information in $_SESSION.

Be careful! When there is a change on data, you must modify the data in db and if successfull also modify the $_SESSION.

In my example, when a user edits his name (which i also store in $_SESSION so i can use it to welcome-tip), i do something like:

If (UpdateCurrentUserData($new_data)) // this is the function that modifies the db
{
    $_SESSION['user']['user_name']=$new_data['user_name']; // update session also!
}

Attention to: session.gc_maxlifetime in your php.ini

This value says how much time the $_SESSION is protected from being erased by the garbage collector (the file that exists on your disk in which the $_SESSION data are stored)

If you set this very low, users may start getting logged-out unexpectedly if they are idle more than this amount of time because garbage collector will delete their session file too quickly

if you set this very high, you may end up with lots of unused $_SESSION files of users that have left your website a long time ago.

also i must add that gc_maxlifetime works together with session.gc_probability where in general you need lower probability for high-traffic websites and bigger probability for lower traffic since for each pageview there is a session.gc_probability that garbage collector will be activated.

A nice more detailed explanation here http://www.appnovation.com/blog/session-garbage-collection-php

Upvotes: 0

Jagjot
Jagjot

Reputation: 6136

You need to use Memcache for this kind of work. To solve the problem of keeping the updated data everywhere you can create functions for fetching the data, for example when the user logs in you, authenticate the user and after that insert all the user data into the memcache with unique keys like :-

USER_ID_USERNAME for user's username

USER_ID_NAME for user's name etc...

Now create some more functions to fetch all this data whenever you need it. For ex

function getName($user_id){
    if(Memcache::get($user_id."_name"){
        return Memcache::get($user_id."_name");
    } else {
        //Call another function which will fetch the data from the DB and store it in the cache
    }
}

You will need to create functions to fetch every kind of data related to the user. And as you said you want to update this data on some major event. You can try updating the data using CRON or something like that, because as tazer84 mentioned users may never log out.

Upvotes: 0

tazer84
tazer84

Reputation: 1823

If any of these don't apply to your app, then please ignore. In general, I'm against using sessions as caches (especially if anything in the session is going to be written back to the DB). Here's why.

  • Editing the session requires a request from the user. Editing a php session outside of the request-response cycle is very difficult. So if a user Alice makes a change which affects Bob, you have no way to dirty Bob's cache
  • You can't assume users will log out. They may just leave so you have to deal with saving info if the session times out. Again, this is difficult outside of the request-response cycle and you can't exactly leave session files lying around forever until the user comes back (php will gc them by default)
  • If the user requires authentication, you're storing private information in the session. Some users may not be happy about that. More importantly, a hacker could imploy that private information to conduct a social engineering attack against the end-user.
  • Mallory (a hacker) might not be able to use the information you put in the session, but she can poison it (ie. cache poisoning), thereby causing all sorts of problems when you write your cache to your permanent storage. Sessions are easier to poison then something like redis or memcache.

TL;DR Lots of considerations when using a session cache. My recommendation is redis/memcache.

Upvotes: 5

mamdouh alramadan
mamdouh alramadan

Reputation: 8528

redis is a good solution if it is available for you (sometimes developers can't install external modules for some reason) what I would do is either go with your Session approach but with encoded/encrypted and serialized data. Or, which I really prefer is to use HTML5 data properties such as:

<someElement id="someId" data-x="HiX" data-y="Hi-Y" />

which BTW works fine with all browsers even with IE6 but with some tweaks, specially if your application uses jquery and ajax. this would really be handful.

Upvotes: 2

Related Questions