How to save $_SESSION variable when it times out on the server - php

I'm doing research on internet behavior. The participants of my study are asked to fill in a questionnaire.
What they don't know is that this questionnaire consists of an infinite series of forms:
whenever they submit one form, they are presented with another one. From their perspective, the questionnaire never ends. It is filled from an array containing thousands of random questions from old studies.
I want to test, how long different users keep going.
I have two options:
Save each form to the database, when it is submitted. Each successive form UPDATEs the same data record with the current page count. This is easy, and I know how to do it.
No data is saved while the user performs the task. The current page count is saved from the SESSION, when the user abandons the task, i.e. when he closes the browser window.
How do I do this? How can I tell PHP to save a $_SESSION variable, when the user closes the browser? Is this even possible in a reliable way, i.e. the solution does not rely on functionality that is not available in all browsers, such as onbeforeunload (which does not work in Opera)?

$_SESSION is profoundly unfit for the task you want to perform. It is designed (and works well enough) as a vehicle to introduce state into an application relying on the stateless HTTP protocol, not to do something on the absence of further HTTP requests.
When relying on a server-sided mechanism, one of the main points to consider is, that session cleanup can happen concurrently, which is not a problem for dumb destruction of a session, but will hand you problems if you want to do something else.
Relying on client-sided code is much worse: What if the user doesn't close the browser, but it crashes? Or the user is on mobile and drives into a tunnel?
My recommendation would be, to understand, that your problem at hand is not one of session keeping, but one of analytics. This would argue heavily into inserting one row per page into a database:
Do your analytics a posteriori: Are you sure, you already know all questions, you want to ask? Only raw data is able to allow you to change or append to your research problem.
Including a timestamp in the rows will allow you to ask for correlation between response time and total time ... was the user doing your survey just as a side-distraction or was he concentrated on it?
Basically you create a specialized log, that can be analyzed by lots of tools - it being in the DB making it easier to query it.

What I do now is save the current state of the session into a database with session_encode() after each form is sent. Before I show any user any page, I check if there is a session with isset($_SESSION['whatever']). If there is none, I check in the database, if a session was stored for this user (they are identified through a login, all this takes place on a site that requires registration). If a session was stored, I drag it from the database and resore it with session_decode(). If there is none, I create a new one. Now, when the browser was closed, the user gets returned to the last page with all variables (of all previous pages) prefilled, including current error messages ("Please choose ..."), if there where any.

Related

Not allowing access to the specific webpage if it is opened by the other person at the same time

I have developed a website in which server side coding is done through PHP and I am using MySQL database. There is a specific page on my site that should be opened only once at a time, that is, if it is opened by one person at the same time, the second person should get a message "This page is opened by someone, you can't use it at this time" I thought of a logic that I store timestamp in the database and compare the time from the database and if it's same as that time then it means the page is opened by the other person so access should be restricted. But I don't find this logic reliable. Could there be any other logic that could be implemented?
Obviously this is quite an open question and impossible to give a complete solution to without actually seeing your database/code.
However, here would be a pretty stable logic:
User attempts to access current page.
1) PHP checks DB if session_on_page is not Y.
1a) If Y: Error Message, page in use.
1b) If not Y allow user to access and set session_on_page_user to the users login id or username etc.
2) On page load, start AJAX session that re-logs Y every 5 seconds along with current username.
2.1) Using JavaScript, check for onunload and run a AJAX function that sets session_on_page to N and also wipes session_on_page_user.
That process will be fine if it's simply for viewing data. If there's also any forms/edits being made whilst on the page I would suggest hashing the current time along with user name to create a fairly secure hashkey that is unique to that user and compare it against server time when performing any updates. You may want to go even more secure than this depending on your case scenario. You could use PHP sessions to double check also and potentially even some Apache handling.
Like I said, it's quite a broad question so we can only really give suggestions to logic.

How to manage multiple tabs with PHP

I have an application that uses several different forms to perform various actions. Some of the forms access data from submissions in other forms.
For example: a user places a new order on one form and adds a new item in another, the items can be added to orders.
So this leads to the possibility that a user may be adding an order and realize that an item must be added first. So naturally a new tab will be opened to do so instead of losing the information added to the order.
Currently I have a $_SESSION['form'] variable to let the form handling script know which function to use after form submission. The problem is that with multiple tabs open, this value will get overwritten by the last opened tab. I have had a couple ideas on how to handle this but so far nothing ideal.
Idea one: use a hash value to identify different page loads and send the hash as a hidden field
$hash = $_POST['hash'];
$form = $_SESSION[$hash]['form'];
Issue: session overloading. This method will make a new session value each time a form is loaded to uniquely identify the form submission. I could unset the value upon submission, but what if a form page is loaded and never submit, or if the page is refreshed. I would prefer to keep the session as light weight as possible.
Idea two: use AJAX to set the $_SESSION['form'] value upon clicking submit
Issue: users that do not use JS. I would like to be able to continue providing support to users that prefer to disable JS if possible, although this method seems like it could be a bit better. However, I am unsure whether there could be browser compatibility issues here.
Idea three: create a hash id for each window
Issue: PHP can't distinguish between browser tabs. This would be the most ideal by far.
Idea four: split the form handling script into multiple files, thus removing the need for a value to select which function to use.
Issue: inconvenient, but I am open to this idea if it proves to be the only real method to handle this issue. It would require a fair bit of re-structuring though.
Any ideas on how to securely manage different tabs and session information in PHP?
This is just my opinion, but I would use idea #1-- each time the form loads, give it a random hash (just md5 of the time() + random number would suffice), and then keep up with those hashes like they are unique window identifiers.
Yes, it might bloat your session a little, but if it doesn't slow down the user's experience, I wouldn't worry about it. If it really bothers you, you can keep track of how many window ID's you've created for the user (in the session) and limit it to 100 or 1000. This would prevent a malicious user from writing a script to open millions of windows.
Remember, when the user's session is destroyed (by logging out/closing the browser), all those hashes are gone too. And if you were REALLY feeling industrious, you could have a system of expiration on hashes. Like, after 2 hours they will be removed from the session.
But honestly-- if it were me, I'd just leave them in the session and not worry about it.
Just my 2 cents,
Richard

Alternative to using $_SESSION variables to solve multiple tab issue

I started writing a web application that stores certain user information in the $_SESSION variable. Usual stuff - user_id, username etc.
I then started using the variables to store certain navigation information. For instance, $_SESSION['organisation_id'] so that wherever the user is in the application, I can easily add 'organisation_id' to any table without having to parse 'organisation_id' across every page request (eg. index.php?organisation_id=456&var2=6 or anotherpage.php?organisation_id=456& etc)
All hunky dory until a user opens a new tab and starts navigating to another organisation so hence creating a new $_SESSION['organisation_id'] value and creating an epic fail on the original tab.
The only solution I can think of is to go back to putting organisation_id into every form and navigation element within the application but yeesh, I'm thinking there must be a more elegant solution.
Normally, I find everything I need on StackOverflow but the answer to this question still eludes me!
"The only solution i can think of is to go back to putting organisation_id into every form and navigation element within the application but yeesh, i'm thinking there must be a more elegant solution."
No there isn't.
Maybe you can check if $_SESSION['organisation_id'] exist, and if so you can write new variable in session with different name, and so one.
Currently there is no way to solve the problem. But to avoid a similar task in the future, I would suggest split up all your files into different includes.
So even if you have to add a couple of variables to the entire site, you could modify 1 file and get it done than doing the whole thing again.
I think this is a logic problem. The session represents a state for the user. This is because HTTP is a stateless protocol in it's essence (it don't know who is who, just undersdants requests and responses).
So the organization_id is a state. If a user can login to just one organization, you just store this in the session var like you did and use it. If the user logs out and in again with another organization_id, it makes sense that only the last one remain available.
If your application has to support multiple organization_id's, you should reflect that logic in your session handling, saving an array of organization ids for instance (instead of just one). But then you have to change your application to allow the user to navigate from organization to organization, etc. There's no point in letting the user be in two organizations at once if the screen just shows one of them.
you can store the value into session during onblur of that username, etc and you can get it before you clicking the next tab
(i.e) using Jquery/Javascript u can get that value of username, etc while onblur and store it in session.
You can resolve this by simply moving the data you currently put into the $_SESSION array into a sub-array within $_SESSION, so that you can store multiple sets of data at once in the session.
It would end up looking a bit like this:
$_SESSION[organisations] = array(
'456' => array('organisationID'=>456, 'otherdata'=>'blah'),
'678' => array('organisationID'=>678, 'otherdata'=>'blah'),
...etc...
);
This will allow you to keep the data for multiple orgs in the session data at once, so you don't have to load all the data every time.
But yes, you will need to send the relevant organisationID with every request, so that your code knows which element of the session data to work with. You can't really work around that. Every request will need tell PHP which orgID to work with.
The down-sides here are that by storing all that data in the session, you're using a lot more memory for your session data, so if there's a chance that the user will browse a lot of organisations during a session, I would advise limiting the size of $_SESSION by dropping data that hasn't been used for a while.
The other down-side is that if this is a multi-user system, storing the data in session means that it will be unaware of any updates made by other users. If you were to load the data fresh from the database on every request, yes it would create more work for the DB, but it would ensure that the data given to the user was always up-to-date.

Storing user info to session or load them directly from sql when request is made?

Another, maybe dummie, question. I'm making a website and now I've dilemma between $_SESSION and requesting user data directly from the table itself. So, my two ideas right now:
Retrieve needed values from mySQL and then set them to $_SESSION array. So, when I need something I can just call $_SESSION["username"]. It has some disadvantages also. For example, if admin changes some user data, ie username(that is a lame example, but still).
Retrieve value straight from SQL. In this case I can call some function what calls a SQL query and gives me result.
So, question is, which method is better to use or there are any alternatives you can suggest.
Thanks.
For frequently-used data but relatively unchanging data, such as names ("Hello, $firstname, welcome back") that would be used on every page request, you probably should cache them in the session. The slight additional parsing/loading overhead will be far less than having to yank that data out of the DB each time.
For relatively critical data, e.g. 'account is disabled', you may want to hit the database each time. However, this would depend on your security needs. If it's ok for a banned user to be able to wander around your system for a short period after their account is disabled, you can implement a time-out counter in the session, e.g. after every 50 hits, you refresh the data in the session regardless.
do not hold username in SESSION, instead hold user id, and don't let the admin to change the user id. once an account created, it's user id shouldn't be modified. and for each page load check stuff from DB.

Maintaining State Between HTML page and PHP Server Page

I am designing a simple drag and drop quiz. We are limiting the number of attempts to get a correct answer to two for each box/answer. However, I'd like to keep the functionality and state of the quiz separate from the display/view.
Currently, as the user attempts to get a correct answer by dropping an answer box on top of a question box, an ajax call is made to a PHP page which returns a 'true' or 'false' value.
We have been evaluating if we want to use Session variables on the PHP page, cookies, or something even more simple to track how many attempts each box has consumed. It would be preferable (for good form's sake) to somehow maintain the state of this data on the server - so the client has no idea what is going on. Session variables seemed to make sense to me - as the user continues to make attempts with different question/answer combos, the server tracks the number of tries and returns (in the ajax response) the result of a user's question (right/wrong, and how many tries that answer has remaining, if any) but I'm wondering if there's a better solution. Any input?
Session seems like a good fit to me. Cookies can be tampered with so I would avoid that if you need the error count to be accurate.
Sessions is probably your best bet. Cookies could be used as well, or if you can guarantee availability of HTML5 localStorage in the browser, you could use that as well.
Unfortunately to keep the functionality separate, there is not. You can use a session variable, or database storage paired with a session id stored in a cookie.
Store current user state into session (temporary storage) and track what he have answered what not etc. at the last step store data into database, or file (permanent storage). Session is individual for every user. Users can't alter your site sessions.
Session usage

Categories