Well, I have a new project, and I've not done anything like it before, but so far so good. I am in need of having to pass some data from one page to another, and there is no limit to the amount of data that gets passed.
At first, I was thinking of POST-ing it, and then when each page loads, just grab the POST data, and store it in an array, but to me that sounds a bit too over complicated or something for what I want to do.
Then I thought about HTML5 and localStorage, but since there is a limit on localStorage, and the fact that the majority of users browsers still don't support it yet (that is, the majority of my clients customers browsers), that's a big no no, at this point.
So, now I'm all out of ideas.
Here's what I'm trying to do, it sounds pretty simple to me, yet I can't figure out how to go about it:
On any given page, there are a probably over a hundred links, each link represents either a name of a product or information about a product, if they click on of these links, and then move off to another page, then the information about what product name they clicked on would follow them to that new page, and then the same thing happens on the new page, if they click on one of those links again, then new info will be added to existing information, and passed on to whatever new page they visit.
I guess you could say that it works almost exactly like a shopping cart, whereby if a user Adds to Cart, their Cart, and all data inside it follows them right to Checkout.
I'd appreciate any help at all?
You are looking for sessions. With the limitation that you shouldn't be storing unlimited amounts of data in a session file, either; better create a temporary file that is named after the session ID, or store the data in a database.
Alternatively, you can also implement a custom session handler.
Either way, Sessions are the standard way of persisting state across page requests for the same user.
You could store the data in a session, or even in a database table (if there truly is "no limit").
For more information on sessions, see Session Handling in the PHP online docs.
I think you really want to use a database for this purpose. Each page pulls the data out of the database as the user clicks through. I guarantee you that for a hundred or so objects from the database, the time to access the database from each new page is an order of magnitude smaller than the round trip HTTP time from the user's browser.
what you are looking for is php sessions.
Yes, for your purpose you should use sessions, I'm agree with others users.
But keep in mind that: sessions expire. If you were looking for a persistent solution, you can store your PHP objects (vars, array, object instances, etc...) using the serialization and unserialization. Using this method you can store your objects in plain text everywhere (eg. DBMS) and restore them at any time. If you're working with objects you can also use the magic methods __sleep() and __wake().
Related
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.
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
I was wondering if using a SESSION variable to pass data from one PHP page to another is efficient. I ask this because I thought that SESSIONS were only used to keep the user logged in to a website, and as an alternative to cookies. Would it not be better to pass data (non-sensitive) from one page to another via a URI such as members.php?name=Joe&age=28?
A PHP session writes a cookie to your browser and then stores the data associated with that session on disk; its about as expensive as an include() to read it back in on the next page load, which is to say completely trivial.
Additionally, the user can't change session data unless you create a mechanism which allows them to; they can mess with the query string easily.
Short answer: Yes, its efficient.
Sessions are useful for lots of things, not just login information. They're great for holding status messages during a POST/redirect/GET cycle or anything else that keeps track of the state of the user's session (hence the name) - but only the current session, not long-term permanent configuration options.
As far as efficiency goes, you need to remember that anything in the session needs to be serialized & unserialized on every page load. Storing a name and age wouldn't add much. Adding a megabyte of image upload would probably be bad.
More important than the efficiency consideration is to remember that session data is only temporarily persistent. If you want to always know that Joe is 28, it should go in the database. If it's only useful on a single page load, it should probably stay in the URL or be POSTed. If you're interested in remembering it for a few minutes, the session might be the place to put it.
Depends on what you're doing. If that page requires that information to function properly and is not behind a login then passing in a query string is the way to go (e.g. search results, product pages). If it is behind a login then using a session would allow you to keep your URLs clean and also make it difficult for users to abuse the page (e.g. swap out data in the query string).
Yes, you can store data and message in SESSION and it is accessible from any page. But remember, SESSION uses browser support to store data. They can be deleted manually by the user
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.
I would imagine it would be done with a cookie or session, but what is the best way to remember an accordion menu's state if a user opens an item and leaves? How can I have "open" items in that state when the user comes back to the site?
I've just upgraded my custom CMS with a new interface, and the new menu needs something like this or usability will suffer greatly.
I don't need specifics, just how you would normally do it.
Thanks!
http://www.shopdev.co.uk/blog/cookies-with-jquery-designing-collapsible-layouts/
this helped me out, hopefully it does for you as well.
I think you would need to save it to a database or use local storage (which isn't supported by all browsers). Cookies would work, but they can be deleted by the user (so can local storage). Sessions wouldn't work because once the user closes their browser, they lose their sessions.
Saving to a database or flat file is the most bulletproof way to do it.
Like most things, it depends.
If this is something that will make a server side request, then storing it in the session global would be completely acceptable.
If it's not, then you would need to find some other method of storing it client side. These would include things like storing it in javascript (only available the page's life), a cookie (like you mentioned) or like Bryan Downing mentioned with local storage. Local storage doesn't have good browser support yet.
Do you want it to be remembered regardless of the computer they log in from? If you do then set a simple value in a table associated to that user as to which item is open so it can be open the next time they return.
I use the jquery UI accordion and it's easy to update a field to which option was last selected so the next time the user comes back I can have that remembered for them. I've done this with a simple ajax call to request the value from the DB and return it to my javascript as a variable that's then used to set the opened accordion section.
If you're not worried about remembering across different devices then a simple cookie should do the trick, just updated the cookie each time a selection is made.