How to Use PHP Sessions to Store Data

Introduction to PHP Sessions


How to Use PHP Sessions to Store Data

by Christopher Heng, thesitewizard.com

Sometimes it's necessary for you to temporarily store data specific to a particular user while he/she surfs your website. For example, you may want to store that user's preferences or the secret word displayed in a CAPTCHA image for checking later. PHP sessions provide you with just such a facility.

What's the Difference Between Storing Data in Cookies and Session Variables?

If you have read my tutorial on How to Create and Use Cookies in PHP, you may be wondering why you might want to bother with sessions when you can already use cookies to store small amounts of data specific to a particular user.

There are undoubtedly a number of differences between the use of cookies and session data. The following are, to me, the most significant difference that will affect your choice of which to use.

  1. Cookies are returned and stored in the user's browser, session data is stored on your web server.

  2. The life span of a cookie can be set to almost any duration of your choosing. PHP sessions have a predetermined short life. The exact life span depends on how your web host has configured PHP on your server.

  3. Depending on how your web server is configured, session data is often stored in a public temporary directory on the server. As such it is possible that other users on the server may be able to peek at the data you store there.

When to Use Sessions Rather than Cookies

The above differences affect your choice of whether you should use cookies or sessions to store your data. Note that the following list is not exhaustive.

  1. When you need the data stored on the server and not your user's browser

    When you set a cookie, the cookie is returned to the user and stored in his browser. Sometimes this is not a good idea.

    For example, some websites have a CAPTCHA test on their web comment forms, where an image showing a few random letters and numbers is displayed and users are supposed to type in those characters to prove that they are human and not some spam bot (program). In order for this to work, the script generating the image needs to store the secret word somewhere, so that the program doing the checking can verify the user's answer.

    In such cases, returning a cookie to the user is not a good idea, since a spam bot, on receiving that cookie, can find out the secret word. You can of course encrypt your secret word before storing it in the cookie, but why bother when PHP sessions is exactly what you need for this purpose?

  2. When the data is transient, and only relevant for the current browsing session

    Since you don't know how long your session data will be stored, it stands to reason that you should only use sessions when you don't really need the data for long periods of time. In fact, the data stored should also not be particularly important, so that it's not the end of world if it's lost because it expired.

  3. When the data does not contain any information that needs to be securely kept

    As mentioned earlier, the session data is kept in a temporary directory on your web server. This is usually a publicly accessible folder that anyone with an account on the computer can read. As such, you should be careful what information you store in your session variables. For example, do NOT store credit card numbers, personal particulars, passwords, user names, and things like that in your session variables.

    While this point may seem like a contradiction to my earlier item about the CAPTCHA secret word, it really is not. Think about it. The CAPTCHA secret word is merely a crude device to distinguish the spam bots from the humans. It's not really a secret -- you even display the word in the user's browser in plain sight. It doesn't really matter if someone on the same web server as you happens to see the secret word currently being used. There's not much that person can do with it, and even if it's possible, so what? At worst, you get a few extra spam messages to delete.

    Contrast that with storing your customers' credit card numbers or passwords. If these are compromised, you will have a serious problem on your hands.

How to Use Sessions in Your PHP Scripts

To use sessions in your script you need to do the following.

  1. Starting a Session

    At the beginning of your script, make a call to the session_start() function. This call should be in every script that needs to utilise the session data. For example, if you have a script that creates a CAPTCHA image and needs to store the secret word for the session, you will need to put session_start() at the beginning of the script. If you have another script that takes the user input for the form and checks the secret word entered by the user against what you stored earlier, you will also need to put session_start() in that script.

    The function session_start() takes no parameters. It always returns TRUE, so you don't have to bother to check its return value.

    When session_start() is first called, PHP sets a cookie (yes, a cookie) in your visitor's browser, containing a session identifier ("session ID"). It also creates a session data file to store variables related to that particular session. If the same script, or another script on your site, calls session_start() later, the PHP interpreter will receive the session ID cookie from the browser and load the variables from the session data file it created earlier.

    Important: since session_start() sets a cookie via the HTTP cookie header, you must call it before you output anything from your script. It's best to simply call it at the beginning of your script.

  2. Storing and Accessing Variables

    To store variables relevant to the session, assign what you want to a member of the $_SESSION array. For example, the following snippet assigns "ABC123" to $_SESSION["secretword"] and a colour to $_SESSION["theme"]:

    $_SESSION["secretword"] = "ABC123" ;
    $_SESSION["theme"] = "purple" ;

    You can assign as many variables as you wish.

    To access those variables, simply reference it as you would any PHP array. For example:

    session_start();
    $captcha = $_POST["captcha"] ;
    $secretword = $_SESSION["secretword"] ;

    if (strcmp( $captcha, $secretword )) {
    // it's a bot
    }
    else {
    // matched -- it's a human
    }

    The above code retrieves the contents of the "secretword" session data and stores it in $secretword. It also retrieves the value returned by a form's "captcha" field and stores it in $captcha. The function strcmp() is then used to compare the contents of the two variables.

  3. Ending a Session

    Ending a session is not as easy as starting one, since there is no simple function to cleanly end it. If you really need a way to end a session yourself (other than by the user simply quitting his/her browser), PHP provides the session_destroy() to destroy the data associated with a session. However, this in itself does not clean up everything. For example, the session cookie is not unset. The $_SESSION array is also still available until your script ends.

    To remove the cookie, manually delete it using the usual method one uses to delete a cookie in PHP. To get the name of the cookie to delete, call the session_name() function, which returns a string that is also the name of the cookie set by the PHP session handler.

    Example code for how you can clean up after a session can be found in the official PHP manual.

Conclusion

With this introduction to PHP sessions, you should be able to code scripts that take advantage of the built-in session handling provided by PHP.

Copyright © 2008-2014 by Christopher Heng. All rights reserved.
Get more free tips and articles like this, on web design, promotion, revenue and scripting, from http://www.thesitewizard.com/.

thesitewizard™ News Feed (RSS Site Feed)  Subscribe to thesitewizard.com newsfeed

Do you find this article useful? You can learn of new articles and scripts that are published on thesitewizard.com by subscribing to the RSS feed. Simply point your RSS feed reader or a browser that supports RSS feeds at http://www.thesitewizard.com/thesitewizard.xml. You can read more about how to subscribe to RSS site feeds from my RSS FAQ.

Please Do Not Reprint This Article

This article is copyrighted. Please do not reproduce this article in whole or part, in any form, without obtaining my written permission.

Related Pages

New Articles

Popular Articles

How to Link to This Page

It will appear on your page as:

How to Use PHP Sessions to Store Data





Home
Donate
Contact Us
Link to Us
Topics
Site Map

Getting Started
Web Design
Search Engines
Revenue Making
Domains
Web Hosting
Blogging
JavaScripts
PHP
Perl / CGI
HTML
CSS
.htaccess / Apache
Newsletters
General
Seasonal
Reviews
FAQs
Wizards

 

 
Free webmasters and programmers resources, scripts and tutorials
 
HowtoHaven.com: Free How-To Guides
 
Site Design Tips at thesitewizard.com
Find this site useful?
Please link to us.