Michael.Lumley Michael.Lumley - 7 months ago 32
PHP Question

Updating PHP Session Variables When Database Changes

Bottom Line Up Front: Is there a way to update session variables from a script on the server running outside the session?

Detail: I am using MySQL to store large amounts of user information. When a user logs in, I store some of that information in $_SESSION, as a way of caching the data in order to cut down on the number of SELECT queries. The user works with the data, and any changes made are saved to the database.

The problem is that the data on the database could change while the user is working with the $_SESSION representation of the data. In that case, one set of changes could overwrite the other. It's not feasible to 'lock' the data in the database while it is being used in $_SESSION.

It would be fairly straightforward to flag the database with a $_SESSION id when the data is 'checked out' and then update the $_SESSION representation of the data, if a script makes changes to the checked out data. I just don't know what (if anything) can be called from a script on the server called outside the session to change the variables within that session.

Answer

After getting your comment, I think this solution will work for you:

when you start session, keep session id in you database: i.e

<?php
session_start();
$sid = session_id(); // suppose o4lb6s392r2mj1vv6nhlrjfmp1
$_SESSION['user_solr'] = 'admin';

you will get a string. when you want alter session data, without refresh user page load, do following to change user's session data:

<?php
session_id('o4lb6s392r2mj1vv6nhlrjfmp1'); // previous session id
session_start();
$_SESSION['user_solr'] = 'editor';

Updated: This will also work:

<?php
session_start('o4lb6s392r2mj1vv6nhlrjfmp1'); // previous session id
$_SESSION['user_solr'] = 'editor';