Home Logo
Show Full Menu
Hide Full Menu


Created: 12/10/10 Views: 2482 myFave Image

In this tutorial we will learn sessions
In this tutorial we are going to look at sessions. Sometimes when you create a website, you are going to have the need to keep certain data saved temporarily during the users browsing experience and this can be done using sessions.
The way it works is that you create a session, and then it is automatically given a unique id so that it doesn't get muddled with other sessions, and then you set the value for that session. Whilst that user still has the same browser open the session will still exist, and will be removed once the user closes their browser.

So why would we really want to use this?
  • To carry data through multiple page forms
  • To create a logged in area
  • To save the user having to insert specific data repetitively
  • To save flexible areas of the page to suit the user

The way to think of a session is to think it's just like a variable that can be called at any time as long as it exists.

To be able to call and create sessions you must first define in your PHP document that you are are going to be using them.
    Enable Sessions in your web page
  • <?php
  • session_start();
  • ?>

    Create a Session
  • <?php
  • session_register('Custom name for session');
  • ?>

    Give Session a value
  • <?php
  • $_SESSION['Custom name for session']= 'value for session');
  • ?>

    Call and Print Session
  • <?php
  • print $_SESSION['Custom name for session'];
  • ?>

That's all it takes, 4 tiny different parts allow you to manage your sessions.
Look at this for an example,
  • <?php
  • session_start();

  • session_register('username');
  • $_SESSION['username']='Ben';

  • print $_SESSION['username'];
  • ?>

  • Ben
So I could now call $_SESSION['username'] in any php script whilst that user is still in the same browsing session.

There will be times when we want to remove the session, or it's value during the same user session. This may be because they have logged out, or the form has already been processed.
    Unset value of session
  • <?php
  • session_start();
  • unset($_SESSION['username']);
  • ?>

By using the unset(); function we are able to give the session no value.

    Destroy session
  • <?php
  • session_start();
  • session_destroy();
  • ?>

This will destroy all the sessions that the user owns.

You should give this a go for yourself, creating a session on one page and then calling it on another, and they destroying it.
Of course like any variable, you can change the value of the session as and when you wish.

back to: PHP Extended

There are no comments