How to Use Sessions in PHP?

“A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.”

PHP Session Variables

When you are working with an application, you open it, do some changes and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn’t maintain state.

A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.

Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.

Starting a PHP Session

Before you can store user information in your PHP session, you must first start up the session.

Note: The session_start() function must appear BEFORE the <html> tag:

Sample:
<?php session_start(); ?>
<html>
<body>
</body>
</html> 

The code above will register the user’s session with the server, allow you to start saving user information, and assign a UID for that user’s session.

Storing a Session Variable

The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:
Sample:
<?php
session_start();
// store session data
$_SESSION[‘views’]=1;
?>
<html>
<body>
<?php
//retrieve session data
echo “Pageviews=”. $_SESSION[‘views’];
?>
</body>
</html>
OUTPUT WILL BE: Pageviews=1
In the example below, we create a simple page-views counter. The isset() function checks if the “views” variable has already been set. If “views” has been set, we can increment our counter. If “views” doesn’t exist, we create a “views” variable, and set it to 1:
oNE mORE eXAMPLE:
<?php
session_start();
if(isset($_SESSION[‘views’]))
$_SESSION[‘views’]=$_SESSION[‘views’]+1;
else
$_SESSION[‘views’]=1;
echo “Views=”. $_SESSION[‘views’];
?>

Destroying a Session

If you wish to delete some session data, you can use the unset() or the session_destroy() function.
The unset() function is used to free the specified session variable:
<?php
unset($_SESSION[‘views’]);
?>
OR
<?php
session_destroy();
?>

More info on Sessions
There is a relationship between Sessions and Cookies — they serve somewhat the same purpose, and are, to a certain extent, usable interchangeably.  Sessions, which were integrated into PHP in version 4 of the language, are a means to store and track data for a user while they travel through a series of pages, or page iterations, on your site.

 

The most significant differences between the two are that cookies are stored on the client, while the session data is stored on the server.  As a result, sessions are more secure than cookies (no information is being sent back and forth between the client and the server) and sessions work even when the user has disabled cookies in their browser.  Cookies, on the other hand, can be used to track information even from one session to another by setting it’s time( ) parameter (see http://www.htmlgoodies.com/php/p14cookies.html)

How Sessions Work

Sessions in PHP are started by using the session_start( ) function.  Like the setcookie( ) function, the session_start( ) function must come before any HTML, including blank lines, on the page.  It will look like this:

<?php
session_start( );
?>
<html>
<head> ……. etc

The session_start( ) function generates a random Session Id and stores it in a cookie on the user’s computer (this is the only session information that is actually stored on the client side.)  The default name for the cookie is PHPSESSID, although this can be changed in the PHP configuration files on the server (most hosting companies will leave it alone, however.)  To reference the session Id in you PHP code, you would therefore reference the variable $PHPSESSID (it’s a cookie name; remember that from Cookies?)

Your sharp mind may be wondering what happens when you come to the second pass through your page and reach the session_start( ) function again.  PHP knows that there is already a session on progress and so ignores subsequent instances of the session_start( )   — phew!!

Using Session Data

Having established a session, you can now create, store and retrieve information pertaining to that session.  You might want, for example, to keep track of items in your visitor’s shopping cart.  Information for sessions is stored in a special directory on the server; the path of that directory is specified in the server’s PHP configuration files.

Information to be stored for a session is kept in session variables.  Session variables are created by registering them for the session, using the session_register( ) function.  To use that information (on any page iteration in the session) you simply reference the variable just like you would any other variable.  Here’s an example:

<?php
session_start( );
?>
<html>
<head>

<title>Using a session variable</title>

</head>

<body>

<?php

print “Welcome to session number: “;

print $PHPSESSID;

?>

<br />

<?php

session_register(“username”);

$username = “Goody”;

print “Your name is: “;

print $username;

?>

</body>

</html>

In this example we have created a session and displayed the session number.  We then registered a session variable called username (notice the quotes around the variable’s name in the call to the session_register( ) function.)

Next we assigned a value to that variable with the ” = ” assignment operator (remember operators from http://www.htmlgoodies.com/php/p05expressions.html?) and then displayed the value of that session variable.

We now have all the basic tools to establish a session, and to create and use variables that last through the entire duration of the session.

 

Hope this Small takeover has helped you to understand Sessions and use of Sessions in PHP

 

Advertisements

5 thoughts on “How to Use Sessions in PHP?

  1. I really wanted to jot down a quick message to express gratitude to you for those superb concepts you are placing on this site. My extended internet search has now been compensated with sensible tips to go over with my colleagues. I d say that we website visitors actually are quite endowed to be in a wonderful site with very many marvellous people with interesting p?oints. I feel somewhat fortunate to have used your entire webpages and look forward to many more enjoyable times reading here. Thanks a lot once more for all the details.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s