Pages

Friday, October 29, 2010

Sessions

Sessions are a way to store and track data for a user while they travel through your website throughout their visit. But wait a minute, I hear you say, isn't that what cookies are for? Indeed it is! In fact, sessions are very similar to cookies, and are used to accomplish the same things. The most significant difference between the two is that cookies are stored on the user's computer, while session data is stored on the server. Sessions are thus more secure than cookies, as no user information is being passed back and forth. The problem with sessions, however, is that they work for one visit only, whereas cookies can track information from one session to another by using the time() paramater. It's up to you, and what works best for your website, which one you choose to use.
Sessions in PHP are started like this:
<?php
session_start( );
?>
As with cookies, the session_start( ) code must be sent before any anything else on the page, including PHP, HTML and blank lines.
Once the session has been started, data can be added to the session by using the $_session variable. To create, for example, a username variable with a value of Kali:
<?php
$_SESSION["username"] = "Kali"; 
?>
Now you can use and read the $_SESSION["username"] variable as you would any other variable in PHP, on any page of your website. Such as:
<?php
echo "Welcome to my site, ";
echo $_SESSION["username"]; 
?>
Which would display: Welcome to my site, Kali
A session ends whenever the visitor leaves your site. If you wish to delete a variable inside the session, the following code can be used:
<?php
unset($_SESSION["variable"]); 
?>
Where "variable" is the name of the variable in question, such as "username".
To end the session alltogether, before the visitor has left your site, such as with a "Log Out" option, this can be done using:
<?php
session_destroy(); 
?>
And that should be everything you need to know about sessions!

0 Comments:

Post a Comment