Using Sessions in an Environment with Registered Users
The examples you've seen so far have gotten your feet wet with sessions, but perhaps additional explanation is warranted for using sessions "in the wild," so to speak. The next few sections will outline some examples of common session usage.
Working with Registered Users
Suppose you've created an online community, or a portal, or some other type of application that users can "join." The process usually involves a registration form, whereupon the user creates a username and password, and completes an identification profile. From that point forward, each time a registered user logs in to the system, you can grab their identification information and store it in the user's session.
The items you decide to store in the user's session should be those items which you can imagine using quite a bitwhich would be inefficient to continually extract from the database. For example, suppose you have created a portal in which users are assigned a certain level, such as administrator, registered user, anonymous guest, and so forth. Within your display modules, you would always want to check to verify that the user accessing the module has the proper permissions to do so. Thus, "user level" would be an example of a value stored in the user's session, so that the authentication script used in the display of the requested module only has to check a session variablethere would be no need to connect to, select, and query the database.
Working with User Preferences
If you were feeling adventurous in the design phase of a user-based application, you may have built a system in which registered users with specific preferences they can set, which would affect the way they viewed your site. For example, you may allow your users to select from a predetermined color scheme, font type and size, and so forth. Or, you may allow users to turn "off" (or "on") the visibility of certain content groupings.
Each of those functional elements could be stored in a session. When the user logs in, the application would load all relevant values into their session, and would react accordingly for each subsequently requested page. Should the user decide to change their preferences, they could do so while logged inyou could even pre-populate a "preferences" form based on the items stored in the session rather than going back to the database to retrieve them. If the user changes any preferences while they are logged in, simply replace the value stored in the $_SESSION superglobal with the new selectionno need to force the user to logout and then log back in again.