I'm using Laravel 5.7. Redis is set up as my cache and and session driver.
In my controller, if I write to my session using either $request->session()->put() OR Session::put(), it will show up when I print my cache for the session id:
print_r(unserialize(Cache::get(Session::getId())));
Note, my primary goal in outputting session data this way is to access sessions that are not my active session.
However, if I write to my session using either of these methods down the line in my domain, they will NOT show up in the cache print, but will show up (along with everything else that does show up in the cache print) if I use:
print_r(Session::all());
I'm perplexed as to what is going on. I verified that what I'm saying is also true when accessing data via the redis cli. Apparently if I write to session in the domain, it is stored somewhere else somehow? Thoughts?
Your cache and your session are two totally different entities, even though they can use the same driver.
A session is used to maintain a relationship with a user. See the PHP session documentation for more details.
A cache is a place where you store and look for commonly accessed data, instead of hitting expensive code or the database. It is ephemeral, and is never guaranteed to hold any data whatsoever.
Why don't you just use Session::get('whatever')?
After seeing your edit:
Note, my primary goal in outputting session data this way is to access sessions that are not my active session.
You should store that data via a more durable storage mechanism than your cache. As I mentioned before, a cache is ephemeral. You can use redis, as it's a key-value store and not a true cache like memcached. Just use it directly as such:
Redis::get('user:profile:'.$id);
Related
I am struggling to find info on PHP's session_set_cookie_params() affect on sessions that are being stored in a database. Have searched SO and google and referred to the manual, but no luck.
1) Is this function still used in exactly the same way as when using the default file storage for sessions?
2) A more generic session question then (file based approach) - when a session expires, is it deleted from the file system, or does that take place with the auto 'garbage collection', the probability of which is set in php.ini?
3) How is the first parameter (session lifetime) handled when using a database to store the session data? Because without a custom function/method, deletion from the database is not possible. Or does the session expire in the same way as file approach, but the garbage collection needs to be handled with a custom function?
I'm using the following article as a go-to at the moment;
How to save PHP sessions to a database
Thanks in advance.
1) This function configures the cookie that php sends to the client so it works as expected. The session_set_cookie_params() function only applies if you use the default PHP session implementation which stores session data on the disk in the folder defined by session.save_path
2) When using php's session implementation garbage collection happens automatically based on the session.gb_* ini settings. Each time a session is started there is a probability that the garbage collector is ran which will clean up all data from expired sessions.
3) You'll need to implement your own garbage collection routines if you use database storage for your sessions. You can use the probability ini settings to determine when to run garbage collection (see gb_probability and gb_divisor). Garbage collection is performed right after starting the session in most cases. That's when you should see if it should run, and if it runs query your database and remove all stale records. This assumes you also store expiration data with your records so you can actually evaluate if the record is stale or not.
That being said, don't reinvent the wheel and use one of the many Session libraries that already implement custom save handlers.
http://framework.zend.com/manual/current/en/modules/zend.session.save-handler.html
http://symfony.com/doc/current/components/http_foundation/session_configuration.html
i am trying to communicate with Memcache as a session handler for Joomla. Following the PHP docs bottom example i have registered memcache a session handler. As soon as a user loads the Joomla site its session id together with other user data is stored into the Joomla database. But now i don't know how to get hands on Memcache to read the serialized session data like can be done with XCache using xcache_get($sessionid) As soon as i create a new Memcache instance as can be seen in the docs top example the session entry is removed from the database. But the session yet exists. This is quite confusing to me. I required to access (read/write) the serialized user session. How can i fetch/set it from the PHP session handler?
I believe the equivalent you are looking for is something like this:
Getting the session:
$session = $memcache->get($sessionId);
Setting the session:
$memcache->set(
'sessionprefix:'.$sessionId, // the session id.
$session, // the actual session itself
false, // set to true to use compression
$expire, // expiration in second
);
I have not used memcache very much but I have read that people usually use a prefix in the key to separate the different types of objects (this is also a common practice with redis, a similar data store). I have used 'sessionprefix:' here but I am sure Joomla has their own specific prefix.
I have a social network type app I have been working on for at least 2 years now, I need it to scale well so I have put a lot of effort into perfecting the code of this app. I use sessions very often to cache database results for a user when a user logs into the site I cache there userID number, username, urer status/role, photo URL, online status, last activity time, and several other things into session variables/array. Now I currently have 2 seperate servers to handle this site, 1 server for apache webserver and a seperate server for mysql. Now I am starting to use memcache in some areas to cut down on database load.
Now my sessions are stored on disk and I know some people use a database to store sessions data, for me it would seem that storing session data that I cached from mysql would kind of defeat the purpose if I were to switch to storingsessions in mysql. SO what am I missing here? Why do people choose to use a database for sessions?
Here are my ideas, using a database for sessions would make it easiar to store and access sessions across multiple servers, is this the main reason for using a database?
Also should I be using memcache to store temp variables instead of storing them into a session?
PHP has the ability to use memcached to store sessions.
That may just be the winning ticket for you.
Take a look at this google search.
One part of the Zend Server package is a session daemon.
Be careful using memcache for that purpose. Once the memory bucket is full, it starts throwing away stuff in a FIFO fashion.
Found this on slideshare about creating your own session server with php-cli.
The single best reason to store sessions in the database is so you can load-balance your website. That way it doesn't matter which server hands out the next page because they are all using the same database for storing their sessions.
Have a look at PHP's set_save_handler() for how to install a custom session handler. It takes about 30 lines to set one up that puts the session in the database, though that doesn't count the lines to make a decent database handler. :-) You will need to do:
ini_set('session.save_handler', 'user');
ini_set('session.auto_start', '0');
... although session.auto_start will need to be in your php.ini (and set to 0).
If the database access is going to be a bit expensive, there are some other things you can do to mitigate that. The obvious one is to have a DB server that is just for sessions. Another trick is to have it poke stuff into both memcache and the DB, so when it checks, if the memcache record is missing, it just falls back to the DB. You could get fancy with that, too, and split the session up so some of it is in memcache but the rest lives in the database. I think you'd need to put your own access functions on top of PHP's session API, though.
The main reason to store session data in a database is security because otherwise you have no way to validate it. You'd store the session ID along with the data in the database and match them to see if the session has been tampered with but you can't use the server's (apache) default session mechanism anymore.
For Storing variables in memcache instead of the session.. have you set up your database query cache? I'd have a look there instead first as it's far easier to deal with than with memcache.
In general, I have the following scenario:
Fetch product and its related data from database
Convert fetched data to php 'product' object
cache product object in session
The cache is readonly, i.e customers viewing products on the site.
But there are calls like getProductIdsByCategory($categoryId) and the productIds from these results are cached too, per user, not using the global cache that I've read about.
A problem is that if someone on the admin side adds a new product and relates it to a category, then customers will not have the new productId come up in their cached getProductIdsByCategory until a new session is started.
Is there a way to clear e.g $_SESSION['x'] from ALL sessions on the server when a new product is added? I don't want to destroy all sessions because customers will then lose their logins etc.
Or should I move these cached productId searches to the global cache?
p.s am using a custom built cache, not memcached or similar.
Thanks
By default, the session data is just serialized files somewhere in your filesystem, and it is possible to go modify all of them to remove the information in question (respecting locking so that you don't step on any currently open sessions).
I don't really recommend it, though. What I would recommend is making a method of signalling that this cached data should be refreshed, like a database-stored timestamp that gets looked at when session_start() happens, and if the cached data is older than the timestamp, the cache is flushed.
Sounds to be like you could do with real shared state through a caching system like memcache.
The only other way that prints to mind is have the application check for flags for dirty cache data and delete it itself, or if your cache is in a database in a parsable serialized form write an expensive script to read them all, but that will create nasty lag with requests that have already read the data.
I would go with real shared state than checking for object copies.
Unless you store sessions in a database, clearing any specific bit of data will be tricky.
I would suggest caching in files rather than user sessions. This way you achieve the same benefits, but you get total control over what is cached and when it gets cleared.
To disable all existing sessions for a particular application, simply modify your application to change the name of the session using PHP's session_name('new_session_name'). This function needs to be called before each call to session_start().
This won't actually clear the current sessions, but it renders them no longer useful for this application.
Yes, you should move it to a global cache. Sessions are not meant to be accessed globally, I hardly think it's possible.
<?php session_destroy(); ?> // To delete whole session
// OR
<?php unset($_SESSION['myVar']); ?> // To delete a session myVar
to clear a session value use:
unset($_SESSION['x']);
you may loop on sessions for that
I'm interested in what is the more efficient way of handling user data in my game. When someone is playing the game, data from the server will constantly need to be queried from the database.
So I want to know if it is more efficient to keep querying the database or to store the data from the first query in a session and then keep using the session every time I need the data.
This is probably a stupid question as I think it is going to be sessions that are better, but it's best to be 100% sure :)
If the data will only be updated by the client session in question, then sure, cache it in the session. If other processes will be updating it, then you need to either reobtain it from the database or work out some method for invalidating your session's cached version.
Shared state goes in the database, unless you are ready to manage shared access yourself, which is a big pain.
Often-updated user-specific state goes into the session (if you issue an UPDATE every time anyone presses a key in your game, your database is dead).
If you need a superfast session architecture, try memcached.
Using sessions will be more efficient. But (assuming the data in the session as cache) any other script not invoked by the user, which updates the dataset you're using, should invalidate the cache somehow.
This means that the cache (now maitained in a session) should be accessible to other scripts. So it might be easier to maintain the cache in files (or you could use php_apc or memcached) instead of sessions.
I think there are many caching classes that are good but the only experience I have is with Zend_Cache and it is really easy to use. It supports APC, memcached, file, etc as backends (a.k.a storage)