PHP Sessions
From JumbaWiki
Contents |
What is a session?
In simple terms, a session is a lasting connection between a user and your website. That basically means that when a user comes to your site, a session is started. When the user leaves your site, that is the end of the session.
Why to use PHP Sessions?
PHP Sessions allows you to basically follow the user through your website, bringing along with it all the data the user may or may not have given you. A good example to start with might be getting the user to enter their name when they first come to the site, and then on each page afterwards, you want to address that person by their name. Something more common might be authentication, where you could check the users level and give access to various levels of data (EG User level 1 may only see the names of members, where-as a level 10 user might see all details of a member).
Using PHP Sessions
Starting a Session
<?php session_start(); ?>
Looks simple, doesn't it. Well, it can be. The above line will start a PHP Session on that page. All pages that you require to use sessions will also require that line. If you are going to use Sessions, it is a good idea to insert that line on every page, otherwise you could find the data doesn't traverse the site with the user. Another thing to note is that it should appear at the start of your code, before anything is outputted to your page.
Assigning Values to a Session
Let's now assign a value that we can echo out on another page.
<?php session_start(); $_SESSION['fruit']="apple"; ?>
$_SESSION is a special variable in PHP known as a superglobal (See also $_POST, $_GET). Each superglobal is an array meaning getting and putting data to them an easier process.
In this example, we assigned the value "apple" to the session, with the keyname of "fruit".
Getting Values from a Session
Now that we have assigned "Apple" to a Session call "fruit", we want to be able to do something with it. Firstly, we extend a little bit on the code above to include a link to another page.
putfruit.php:
<?php session_start(); $_SESSION['fruit']="apple"; echo '<a href="getfruit.php">Get Fruit Preference</a>'; ?>
Now lets display what fruit it is we like.
getfruit.php:
<?php session_start(); echo "The fruit I like is ".$_SESSION['fruit']; ?>
Now when you go the the next page, it should return the line "The fruit I like is apple".
Conclusion
So there you have it, a very simple example of how sessions can carry data from one page to the next for your users. Hopefully you now understand how sessions can help you develop more interesting websites to give your users a better web viewing experience.

