38

I've only seen examples of session variables being used to store small amounts of data, like a single user id. I'm wondering if it would be more efficient to instead hold more frequently accessed data in the session variables to avoid querying the database.

For instance, I made a user class that gathers regularly requested data for that user upon construction (their user id, username, email, password and arrays of site specific data) and I hold this instance as a session variable. After the user's initial log in, the database rarely has to be queried to get information about the user because it's already in memory.

Am I actually being more efficient at all, or am I just bogging down the system with memory usage?

Side note - I actually find it easier to grab data from the session instead of having to worry about optimising my queries and stuff, so I really hope I'm not being an idiot.

3
  • 3
    well, sessions shouldn't be a dumping ground for megabyte/gigabytes of data, but also you shouldn't be hitting the db for every little minuscule datum. you'll have to find the right balance yourself.
    – Marc B
    Jul 9, 2013 at 17:56
  • Depends on your session handler, by default it writes to flat files which is slower than database. If you enabled database based session handling then you are still making database calls to handle the session data. Perhaps a faster way would be to set your session handler to store/retrieve from a cache backend. Jul 9, 2013 at 17:58
  • And don't forget than when talking about databases, there is alternative/complement to SQL databases. For example, you could use a key/value store like memchached to efficiently store and retrieve data using a key stored in the user session (or in a cookie) Jul 9, 2013 at 18:01

4 Answers 4

42

Firstly, PHP sessions aren't stored in memory by default, they are stored on disk, so every block/session you write to is going to occupy disk space and not memory (until you use PHP to read the session data).

Yes, you're potentially being more efficient, but not if you want to scale and here's why:


Storing data in sessions

It's perfectly acceptable to store some data in sessions. Theoretically, there is no limit (although I've never tried to break it or even push it, just move to a more efficient solution). You will however, be limited by disk space and PHP memory_limit().

Often, data stored in sessions includes things like:

  • Usernames
  • Hashes
  • Registration dates
  • Other variables (user group ids/keys etc)
  • Flash messages
  • (NOT passwords!)

However, there is a tradeoff. If your traffic (and usage) increases and you're storing a lot of data in $_SESSION, you will very likely start to see problems, both in terms of disk and memory usage.

I don't think there is any issue with what you're suggesting, but beyond the items you've listed and where the examples above overlap, care is required.

If you want to scale (horizontally) and retain disk-based sessions then you have options (sticky sessions or storage area network are a couple) as the disk on one server doesn't store the same sessions as a disk on another server.


Session data location

You can find the location where PHP stores session data by calling: session_save_path()

or on the CLI:

php -r 'echo session_save_path(), "\n";'

You've not mentioned your OS, but common locations for the session files (across different OS types) are:

/tmp 
/var/lib/php5/
/var/lib/php/session
c:/wamp/tmp

Sessions stored on disk usually have filenames that look like this using ls -al:

-rw-------  1 www www      0 2013-07-09 20:12 sess_bdsdjedmvtas5njhr5530b8rq6

It's worth noting that there are often garbage-collection processes that clean out dead sessions after specific periods. It does vary by OS, but they are usually present with various LAMP-based installs.


Other session storage options/approaches

In your database
Session data is often stored in a DB instead of on local disk and this works well for both micro, small and (depending on how it's done) medium sites with a reasonable level of traffic.

Like any other solution it has it's pro's and con's (like being able to ban/kick out a user by running a query rather than deleting a session file from /tmp)

In memory
for larger, (higher traffic) sites and particularly where the volume of concurrent users is high, memory is quicker to read/write to for very frequently accessed variables or data instead of adding undue load to your DB. It can and should still be written to the DB (See write-through caching), but also be held in memory for efficient access.

One technique of particular merit is memory caching. A widely used example PHP-compatible open-source solution is Memcached, which can be used on one server or many [distributed]. I've seen this used by small firms as well as large and you only have to look at who uses it/contributes...

3
  • 1
    Why don't store a password in the session?
    – and-bri
    Aug 26, 2017 at 13:57
  • 2
    @and-bri because in a worst-case scenario of session hijacking, you'd be toast! Dec 22, 2017 at 9:16
  • Generally How much memory a session variable take with 3 fields? Aug 21, 2022 at 7:24
6

It all depends on server resources, and on simultaneous users of your website / app.

You can do a rough calculation, by estimating the average session memory each user will need, multiplying it by the average number of simultaneous visitors, and comparing this to the memory you have available for PHP in the server.

This calculation will help you estimate how much is too much in your scenario, in a very rough, but helpful way.

EDIT: by memory I mean RAM and/or disk space, depending on your setup.

2

Some of the other answers assume you mean using PHP sessions to cache data. This is a good solution to store ephemeral data that you need to be available from one request to the next.

But I wonder if you mean using MySQL user-defined variables. You can store long strings of data in these variables, and they occupy RAM in the scope of your database thread on the MySQL server. But these user variables do not stay in memory after your session closes. They are not a good way to store data from one request to the next.

The only reason to store large amounts of data in user variables is that you need to use them in subsequent SQL queries during the same db session (which means during the same PHP request), and you're hoping to avoid transferring that string from the db server to your app. Otherwise, you might as well fetch the result and store it in a PHP variable.

Another solution for storing ephemeral data is to use memcached. You can store data directly, or you can use memcached as a backing store for your PHP session.

1

Try to keep in mind that the web paradigm encourages a stateless memory model. That is to say, load what you need to render the page, render the page, and release the resources.

Obviously there are times to cache data, but yes, storing information in session variables creates more memory usage for your application as a whole, and EACH SESSION will use whatever N bytes you are storing.

If you don't have a performance problem, don't worry about caching. On the other hand, if you want to cache and it's only on one server for a small number of users, don't fret it. Just be aware of the drawbacks of using session variables across a web farm (if you use one).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.