what are the consequences of storing more variables in session? - php

whats the performance issues when we are storing 2-3 extra variables in session??
for:
to save 1-2 queries(per page load)?
To make code simpler?
Hit rate to the website is normal..
Edit
#all I m talking about two three session variables...simple values like number,ids etc

Every time a PHP script/page that uses sessions is accessed, the session data has to be read.
By default, that data is stored on disk as files (you can override that and use a database, for example)
So, basically, for every page load some amount of session data has to be read (and, very likely, written) by PHP. The more data you store in a session, the bigger the session files get.
If you only store a few variables, there is no problem. But if you start storing something like huge arrays, you'll run into problems if your hit rate increases.
--
If you want to "keep code simpler" by storing as much data as possible in a session, you might create more problems instead. For example - should you want to enable API access in the future, you'll possibly have to remove a lot of session data storage/retrieval code and replace it with other methods.
--
Might be unrelated to your problem:
If you want to store some sort of global application state in a session so you don't have to recalculate it, you should use some other caching methods instead of sessions.

There wouldnt be a performance issue. You can store objects and variables, in the session, and it wouldnt make much of a degrade of performance.

Actually, it sounds like you're going to end up saving yourself a bit, performance wise. If these values are simple strings or numbers, or even small arrays or objects, this will be your better option. If you are saving an array with thousands of key => value pairs, however, then it might be better to re-run the query, depending on whether you will need it in given circumstances.
Just remember, that each time you refresh, you will be firing the constructor of each object stored in the session variable. Big objects = heavy payload.

Its not as much of a performance question than it is practicality. Its obvious to me by reading your question that you would not contemplate storing huge arrays in a session.
The issue becomes practical when some action by another user needs to influence values stored in a current session, i.e. an array of bools that shows what a user can and can not access. Having those cached in a session makes revoking permissions impractical.
There's no reason to avoid storing strings and values that are considered to be immutable, or which can easily be re-set by an action of the current user (i.e. changing their user name).

Related

Is it good practice to store large Data in session variable?

I am currently programming a php site, which atm needs to query a large amount of data (about 4 - 5MB) everytime. I already have a session going and wanted to ask, if its good practice to store that data in the session variable?
The current plan is to also maintain a table in the Database containing when a table has changed last. If that timestamp would be newer, then the data would be queried again, if not, use the data of the session variable as its still consistent...
Is this a good way to avoid querying too much data? And what speed impacts would the site have when a session is about 5MB in size?
Thanks in advance!
It's not really good practice (it will make PHP chew far more memory than it really should), but I'm not sure how it will affect performance.
I suppose the real question is this: Why do you need to store so much in the session? If it's information that is meant to be accessible between sessions, then you should be storing it in a database and loading it 'at need'.
If it's binary data (images, files, etc.) that are only relevant while the session is valid, then store it in a temporary file for the user (look at tempnam() and sys_get_temp_dir()), then store the temporary filename on the session.
No, it's not good practice to do this.
Points to consider:
By defailt, the session data is stored on disk in a temp folder. Every time you call session_start() (ie every page load), it will have to load the whole of that data into memory and populate it into the session array. If you're loading large amounts of data, this could have performance implications.
Also, since you're loading this large chunk of data every time, it means that each page load will take more memory. This reduces the number of concurrent users that your server can support.
If you're doing this for caching purposes to reduce hits to your DB, there are much better solutions available. APCu, Memcache, Redis and others can all do a much better job of caching your data than your proposed custom-written solution. There are also wrapper libraries available that make it even easier and allow you to mix and match between caching solutions. If you're using a framework like Laravel or Symphony, there may be caching classes built into your framework. Alternatively, you could try a stand-alone library like phpFastCache. But also, don't forget that modern DB engines have their own caching mechanisms built in, so repeated calls to the same or similar queries should be reasonbly fast anyway.

Is it a good and safe way using session to store site configuration?

I'm using PHP and MySQL. There are some site configuration variables that I need on every page, such as site_url, site_path, contact_email, default_timezone...etc.
Instead of retrieving these values from database on every page refresh, I stored them in session on the first page visit.
I'v been using this way for a while, and I haven't encountered any problems. The only disadvantage I see now is if a value if changed, I have to close browser to clear session and then reload. (but these values are pretty much static)
I'm wondering if this is ok. Is this gonna cause any other problems?
And, how much info can I store in session? Is there a limit?
Some of those sound like they're global values, common to all users. That's a poor candidate for a session value. It'd be better to store those in a file somewhere. There's no point in storing "site_url" for 50,000 sessions, if it's the same value for each of them. Waste of time and space.
Session storage should be execlusively for per-user data, things which aren't/can't be shared between multiple users.
There's no practical limit to session storage, other than how much disk space you have, PHP's memory_limit, and how much cpu time you're willing to waste parseing multi-megabytes of data for every hit on your site.
There's no limit in how much you can store in a session but there's a limit of how much memory php can use http://ca.php.net/manual/en/ini.core.php#ini.memory-limit
This depends on how many users you expect. In anything more than a few dozens at a time, storing this information in session data isn't a good idea.
The session shouldn't really act as a cache in this case. The issue is that if you have 10 thousand sessions, then the session data has to be duplicated 10 thousand times. This isn't efficient.
If your project size warrants it, you'd be better off using something like memcached (or APC cache) to store the cached values for a given period of time. If you're using a database class to handle the config, have the DB class fetch from the cache for you so all places that call the code can do it without worrying about the implementation. You can try to use files as a cache mechanism, but you'll have to worry about cache time outs and file access in that case. Measure before making a decision.

Is it faster to recreate an object or store it in a session variable?

Sorry if this seems obvious to the non-noob. Is it faster to:
Recreate an object instance each time someone goes to a page during a session
or
Store the object instance in a session variable when it first gets created, then always grab it from there when the page is accessed again
I'm not sure if this will turn out to be a "How long is a piece of string?" sort of question, but if it does, then perhaps you could let me know what factors are involved in making the decision?
Session data is stored as text, not binary data so somewhere behind the scenes when you toss it into the session the object is recreated anyway. It's probably a little bit slower than initializing it yourself since it has to do some string parsing but I doubt it's much to worry about. In short, it probably doesn't make a difference either way.
It certainly depends on how much logic is done, when the object is created. You should do some benchmarks with both variations.
Without measuring it, i'd say storing and retrieving should most times be faster.
For recreating objects you have to call possibly multiple constructors, etc, whereas retrieving shouldn't invoke any function calls.
It obviously depends on what fields you have in object, how many of them and how they are populated. Instantion of an object occurs every time you load a page anyway, so it's the matter of fields and their sources.
Just be wary of trying too hard to optimise this. Bear in mind that storing items in session can be heavy, particularly if your site is high traffic.
Also, I've seen a lot of people create an object, which accesses a database and loads it's attributes. This then gets stored in session, updated on postback and then saved back to teh database.
This is fine, but it makes for difficult concurrency checking - say your object has a timestamp of the last time saved - if you reload it each time prior to saving, you can easily check if the timestamp has changed since the last load, in which case you may need to stop the save from going ahead.
Either way, the difference is not going to be huge.

Cache data in PHP SESSION, or query from db each time?

Is it "better" (more efficient, faster, more secure, etc) to (A) cache data that is used on every page load in the $_SESSION array (but still querying a table for a flag to reload the data fresh), or (B) to load it from the database each time?
I'm using the cache method (A), but I'm worried that with hundreds of users, memory could become an issue? It's just simple data, like firstname, lastname, birthday, etc.
With either method, there's still a query being run. Thoughts?
If your data is used on every pages, and is the same for all users, I wouldn't cache it in $_SESSION (which means having a different copy of that data for each user), but with another mecanism, like :
file
In memory, with APC for instance (if only 1 server)
In memory, with memcached, for instance (if you have several servers)
If your data requires long calculations or several DB queries to be obtained, caching it in database could be another possibility (would mean only 1 query to fetch back, and less calculations)
If your data is not the same for each user (which seems to be the case in your situation, as you are caching names, birthdates, ...) :
I would make sure I only cache what is necessary
Once you only have a few data to cache, putting it in session should be quite OK
If you really have that many users, you'll probably have some other scalability problems, and will most likely come to use something like memcached anyway ; which means you'll have some other way of caching ;-)
As a sidenote : if you are doing the same query over and over again, you DB server should cache it by itself (for MySQL, it would go into the "query cache") ; so, it would not be as bad as you think, I suppose -- even if not that much optimized ^^
It depends on what you're session handler is. Your session handler could be MySQL, and thus the question would not be which is better, but how to optimize your session handling.
The default PHP session handler is files, but it can be changed to mysql quite easily.
If you're talking about non-user specific data, then just save it to the DB. Worry about optimizing if you run into problems later. It is usually much more beneficial to use a better design pattern then thinking about optimizing before hand. Design your code so you can easily use a different handler for storage, and you won't have optimizing problems later.
If it is user specific, use the session, but use an appropriate session handler if necessary.

Heavy sessions slowing website

I am programming in PHP mysql.
I have recently got into OOP programming.
So I need to serialize my objects and store them to SESSIONS. However I think the huge sessions are slowing down refreshing and loading of my webpages.
Is there an alternative approach (than serializing deserializing) so that I can still share my objects from webpage to webpage and improve loading time.
Thanks
Rahul
You should first analyze what the actual bottleneck is. Is it really the object serialization/deserialization?
If so, ask yourself, if all the objects need to be present on every request or if they can be reconstructed on demand. Then you could just store the key values to reconstruct those objects instead of the whole objects.
But if you need all those objects though, use more performant storage location than the default (files in the file system), maybe the memory (memcache).
Are all the objects you store necessary from page load to page load? If not then you need to keep those objects out of the session and only reconstruct them on the pages that you need them.
Every object you store in the session will get serialized and unserialized on every page load regardless if you actually need it. So you'll want to keep that to a minimum.
Another option is store only what you need to reconstruct the object in the session and not the entire object. For instance you can store a database id in the session and reconstruct the objects from the database when you need them.
As a rule of thumb you should try to limit your Session-size to 4KB or less (independent on what programming language you use). If your data get's bigger than that, you should start using Tables in a Database (like MySQL/PostgreSQL/...) to persist the data.
Example: Store a draft for a Blog Article
In the Session (with all it's images etc) vs
In the Article-DB-Table (where a flag draft=1).
Believe me, it's more convenient if you choose the DB (and you don't have to hassle with serialization).

Categories