Caching variables in the $_SESSION variable? - php

I'm making a php web application which stores user specific information that is not shared with other users.
Would it be a good idea to store some of this information in the $_SESSION variable for caching? For example: cache a list of categories the user has created for their account.

This would be an appropriate use of the session mechanism as long as you keep this in mind:
Session does not persist for an indefinite amount of time.
When pulling from session, ensure you actually got a result (ASP.NET will return NULL if the Session has expired/cleared)
Server restarts may wipe the session cache.
Do this for convenience, not performance. For high-performance caching, choose an appropriate mechanism (i.e. memcached)
A good usage pattern would be like this (ether cookies or session):
User logs in
Store preferences (background color, last 10 records looked at, categories) in session/cookie.
On rendering of a page, refer to the Session/Cookie values (ensuring they are valid values and not null).
Things not to do in a cookie
Don't store anything sensitive (use session).
A cookie value should not grant/deny you access to anything (use session).
Trap errors, assume flags and strings may not be what you expect, may be missing, may be changed in transit.
I'm sure there is other things to consider too, but this is just off the top of my head here.

That could work well for relatively small amounts of data but you'll have to take some things into consideration:
$_SESSION is stored somewhere between requests, file on disk or database or something else depending on what you choose to use (default to file)
$_SESSION is local to a single user on a single machine.
sessions have a TTL (time to live), they dissapear after a set amount of time (which you control)
Under certain circumstances, sessions can block (rarely an issue, but i've run into it streaming flash)
If the data you mean to cache is to be accessed by multiple users you're quickly better off caching it seperately.

If you only want this data available during their session, then yes. If you want it available tomorrow, or 4 hours from now, you need to save it to a database.
Technically you can modify the sessions to have a very long lifespan, but realize if they use a different computer, a different browser or flush their cookies they will loose the link to their session, therefore anything serious you should create a type of user account in your application, link the session to their account and save the data in a permeate place.

Related

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.
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.
You can also go for local-storage in HTML5, check The Guide and THE PAST, PRESENT & FUTURE OF LOCAL STORAGE FOR WEB APPLICATIONS
Local Storage in HTML5 actually uses your browsers sqlite database that works as cookies but it stores data permanently to your browser
unless someone by force remove the data from the browser finding the data files
Or if someone remove/uninstall browser completely,
or if someone uses the application in private/incognito mode of the browser,
What you need to do
Copy the schema for required tables and for required columns and update data at a regular interval
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.
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.
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.
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
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.

Is it bad to store $_session variables for every user?

Question basically says it all. I get a lot of traffic, about 200k hits a day. I want to store the original referrer (where they came from) in a session variable for various purposes. Is this a good idea or should I stick in a database instead?
You can do both at once :). PHP allows you define the storage logic of your sessions in scripts. This way it is possible to store sessions in a database as well. Check the manual of set_session_save_handler()
Using a database would have its advantages if you use load balancing (or plan to do it once). This way all web servers could read the session data from the same database (or cluster) and the load balancer would not have to worry about which request should be forwarded to which web server. If session data is stored in files, which is the default mechanism, then a load balancer has to forwared each request of a session to the same physical web server, which is much more complex, as the load balancer has to work on HTTP level.
You could just store the information in a cookie if you only need it for the user's current session. Then you don't need to store it at all on your end.
There are a few down sides as well:
They may have cookies disabled, so you may not be able to save it.
If you need the information next time you may not be able to get it, as it could have been deleted.
Not super secure so don't save passwords, bank info, etc.
So if needing this information is required no matter what, maybe its not the way to go. If the information is optional, then this will work.
The default PHP session handler is the file handler. So, the pertinent questions are:
Are you using more than 1 webserver without sticky sessions (load balancing)?
Are you running out of disk space?
Do you ever intend to do those?
If yes (to any), then store it in a database. Or, even better, calculate the stuff on every request (or cache it somewhere like Memcached). You could also store the stuff in a signed cookie (to prevent tampering).

ASP.NET or PHP: Is Memcached useful for storing user-state information?

This question may expose my ignorance as a web developer, but that wouldn't exactly be a bad thing for me now would it?
I have the need to store user-state information. Examples of information that I need to store per user. (define user: unauthenticated visitor)
User arrived to the site from google/bing/yahoo
User utilized the search feature (true/false)
List of previous visited product pages on current visit
It is my understanding that I could store this in the view state, but that causes a problem with page load from the end-users' perspective because a significant amount of non-viewable information is being transferred to and from the end-users even though the server is the only side that needs the info.
On a similar note, it is my understanding that the session state can be used to store such information, but does not this also result in the same information being transferred to the user and stored in their cookie? (Not quite as bad as viewstate, but it does not feel ideal).
This leaves me with either a server-only-session storage system or a mem-caching solution.
Is memcached the only good option here?
Items 1 and 2 seem to be logging information - i.e. there's no obvious requirement to refer back them, unless you want to keep their search terms. So just write it to a log somewhere and forget about it?
I could store this in the view state
I'm guessing that's a asp.net thing - certainly it doesn't mean anything to me, so I can't comment.
it is my understanding that the session state can be used to store such information
Yes - it would be my repository of choice for item 3.
does not this also result in the same information being transferred to the user and stored in their cookie?
No - a session cookie is just a handle to data stored server-side in PHP (and every other HTTP sesion imlpementation I've come across).
This leaves me with either a server-only-session storage system or a mem-caching solution
memcache is only really any use as a session storage substrate.
Whether you should use memcache as your session storage substrate....on a single server, there's not a lot of advantage here - although NT (IIRC) uses fixed size caches/buffers (whereas Posix/Unix/Linux will use all available memory) I'd still expect most the session I/O to be to memory rather than disk unless your site is overloaded. The real advantage is if you're running a cluster (but in that scenario you might want to consider something like Cassandra).
IME, sessions are not that great of an overhead, however if you want to keep an indefinite history of the activity in a session, then you should overflow the data (or keep it seperate from) the session to prevent it getting too large.
C.
Memcached is good for read often/write rarely key/value data, it is a cache as the name implies. e.g. if you are serving up product info that changes infrequently you store it in memcached so you are not querying the database repeatedly for semi static data. You should use session state to store your info, the only thing that will be passed to and fro is the session identifier, not the actual data, that stays on the server.

Am doing online Quiz type of script in PHP. It is better to use cookies or sessions

Am doing online Quiz type of script in PHP. User needs to attend 50 Question in 45 minutes.
After that time it should close the page or Submit the answer to the next page.
It is better to use cookies or sessions. How can i do that.
Am novice in session concept so can u suggest the suitable code.
Awaiting the earliest reply
I assume, as this is a quizz, you'll count point, record ranks, etc. So your users will eventually try to cheat.
Therefor, I would recommend sessions which are only server-side.$_SESSION is an array, like $_GET and $_POST, unique to every user using your website. You can put and retrieve anything when you want.
The only thing client side is a special cookie, called PHPSESSID, which is your visitor's id, used by PHP to retrieve his $_SESSIONarray.
Only things you have to do is to begin every page with session_start(); , before any instructions (except if you use buffering like ob_start())
The main difference between cookies and sessions is where the data is stored.
With cookies, you send the data to the browser, and the browser keeps sending it back to you with every request thereafter.
With sessions, you're storing the data in memory, and then just setting one cookie that has an ID to identify the chunk of space in the server's memory where the data is stored.
The crucial difference is that when the data is stored in cookies:
it can be edited by the user
it can be seen on the network as requests are made
it adds to the weight of each request in additional bandwidth required
it takes up less server memory
When data is stored in the session:
it can't be accessed by the user without going through you
it's not sent back and forth with each request (only the session ID cookie is)
but it takes up memory on the server
it can cause issues on larger sites when needing to move to multiple web servers
I would say it depends on scale. For a lot of questions, those cookies will get heavy and make each request very large. If you quiz is running in an environment that is spread across multiple front-end web servers, sessions might be out of the question.
I suspect the deciding factor is going to be the integrity of the quiz though. If it's crucial that the user can't change the data (such as previous answers, a running score or a timestamp for the start of the quiz) then you'll need to store the data out of their reach, which means using sessions.

Safe timeout value for codeigniter session class?

I am using codeigniter's session class to handle my PHP sessions. One of the session variables automatically created on every visit to the site is session_id:
The user's unique Session ID (this is a statistically random string with very strong entropy, hashed with MD5 for portability, and regenerated (by default) every five minutes)
On my site I need to have functionality to track unregistered user's and I currently have this implemented by comparing the visitor's session_id with a stored id value in a VISITOR table in the database. This works perfectly except for the fact that the session id times out every five minutes. I would like my application to remember visitors for longer than 5 minutes (kind of like what SO does when you post a question or answer without registering).
My question is this: can you see any security issues with simply extending the regeneration time of the session class (to something like 12 hours)?
Update: based on the answers I've seen so far, it seems like its more of a performance concern rather than a safety issue. Its kinda weird how the codeigniter session class works because when creating a new session, it also creates a new cookie which seems to persist as long as the session. I guess I could create another cookie with the session ID that lasts as long as I need it to. But how much of a performance concern would it be if I were to save the sessions for something like 12 hours? Would it slow things down unless I have millions of unique visitors within a 12 hour period (in which case I'd have bigger problems to worry about...)?
Two things with that idea :
If users go away from their computer (without locking it / closing their browser), someone else might use it to go to your site with their account
well, that's probably not your problem
if you have some login/password fields, your users probably already have their login+password memorized by the browser anyway (well, for the registedred ones, anyway -- and those probably have more "power" than not registered ones)
If you have lots of users on your site, you will have more session files
as sessions are stored in files
(same if they are stored in DB / memcached -- in which case you must ensure you have configured memcached so there is enough RAM to store more sessions)
So, yes, there is a small security risk ; but I don't think it is really relevant.
Another idea would be to keep a short session lifetime, but to store some informations in cookies, with a lifetime more important than that ?
Enough information, actually, to allow re-creation of a new session, without the user noticing anything ?
But, yes, that would require a bit more work on your side...
To add a bit more precisions after your edit :
Its kinda weird how the codeigniter
session class works because when
creating a new session, it also
creates a new cookie which seems to
persist as long as the session.
This is the "standard" way of dealing with sessions -- at least, in PHP :
The session's data is stored in a file, on disk, on the server
and a cookie is used to keep a "link" between a user, and the file containing his session's information. Without that cookie, there would be no way of knowing which one of those files contains the session of a specific user.
But how much of a performance concern
would it be if I were to save the
sessions for something like 12 hours?
If you're having millions of users on your site, this will means having millions of files, each one containing the session's data of one user -- and it's not good to have too many files.
But is you are having a few hundreds user, that should be allright, I guess.
Depending on the amount of visitors to your site, saving sessions for 12 hours may not be a good idea. Why not use cookies? This is dependent on whether or not the user has it enabled in his browser though: http://www.php.net/setcookie.
One Security Tip:
Leave True on sess_match_useragent(application/config/config.php)

Categories