PHP has a great set of functions that can achieve the same results of Cookies and more without storing information on the user’s computer. PHP Sessions store the information on the web server in special files. These files are connected to the user’s web browser via the server and a special ID called a “Session ID“. This is nearly 99% flawless in operation and it is virtually invisible to the user.

Session Start

The correct way to start a session is using the session_start() command. We must include this statement at the start of every script of our site that we want to be able to use session variables in. This is essential and an easy thing to forget.

<?
session_start();
   print "We have started our session:";
?>
Common Error: Just like Cookies you MUST call the session_start() function before anything is output to your web browser. This is absoultey important because you will get some ugly errors by PHP that will say something like this:
<?
echo "This is incorrect and will cause an error:";
 session_start();
?>

Generates the error:

Warning: Cannot send session cookie – headers already sent by (output started at session_header_error/session_error.php:2) in session_header_error/session_error.php on line 3

Assigning Variables

<?
 // start the session
 session_start();
 print "Registering a session";
 // Get the user's input from the form for example
 $data = $_POST['data'];
 // Create a new Session variable. You can skip this step. A variable can be automatically registered when you assign it a value.
 session_register('name');
 // way of putting data into the variable. If variable ‘name’ is not already registered, then it will be automatically registered and assigned a value here.
 $_SESSION['name'] = $data;
?>

Sessions on Multiple Pages

  • The first thing you MUST do on each page you want to access a session variable is to start the session.
  • That may not sound right to you because “We already started the session on the last page.”
  • That’s true, but we need to keep the “connection” going between our session because they do not have persistent connections like MySQL does.

A Multiple Page Session

<?
// start the session session_start();
   print "In this script we use session variables";
   print "that we created in the previous script<br>";
   // display the session variable
   print "Hi there $_SESSION['name'] everything is working fine! <br>";
?>

Unregistering Session Variables

PHP is really well designed. With PHP Sessions, we have the ability to simply remove a single session variable without dumping our entire session and rebuilding it. The function is called session_unregister(). Here’s how we unregister a single session variables and leave the rest intact.

session_unregister(‘name’);

Destroying a Whole Session

Why might it be necessary to destroy a session when the session will get destroyed when the user closes their browser? Well, Imagine that you had a session you were using to determine if the user was logged into your site based upon a username and password – anytime you have a login feature, to make the users feel better, you should have a logout feature as well. That’s where session_destroy() may be useful – it will delete the session files and clears any trace of that session.

Practical Sessions : Hit Counter

What we’re about to do here is:

  • Start your session.
  • Register a variable called “count”.
  • Assign a value of 1 to it on the first page.
  • Then, we’re going to increment the counter as we go through the website.
  • We’re also going to provide a reset page.

Hit Counter – counter page (hit_counter.php)

<?
 session_start();
 if (!$_SESSION[‘count’]) // or if(isset($_SESSION["count"]))
 session_register('count');
 if($_SESSION['count'] == 0)
 $_SESSION['count'] = 1;
 else
 $_SESSION['count']++;
?>
You've visited <?=$_SESSION['count']?> pages so far!<br>
<a href="hit_counter.php">Increment Your Counter!</a><br>
<a href="reset.php">Reset Your Counter!</a><br>

Reset Counter (reset_counter.php)

<?
 session_start();
 session_register('count');
 $_SESSION['count'] = 1;
?>
You've visited <?=$_SESSION['count']?> pages so far!<br>
<a href="hit_counter.php">Increment Your Counter!</a><br>
<a href="reset_counter.php">Reset Your Counter!</a><br>

That’s it. Pretty easy! :-)

Viewing Your Session ID

Every Session has a unique Session ID. A session ID looks like some chatting guru collapsed on the keyboard. There’s a function in PHP called session_id() that allows you to display the current session ID or utilize it however you need.

<?
 session_start();
 echo "Your session ID is <B>". session_id() ."</B>";
?>

This will simply display something like:

Your session ID is Bd315d2ed59dfa1c2d0fb0b0339c758d

Practical Sessions : User Prefs

You can set user preferences using Sessions. Following sample code tells you how:

 <?php
session_start();
if((!$_SESSION["body_color"])||(!$_SESSION["text_color"])) {
$_SESSION["body_colour"] = "#000000";
$_SESSION["text_colour"] = "#FFFFFF";
}
?>
<HTML>
<BODY BGCOLOR=<?=$_SESSION["body_colour"]?> TEXT=<?=$_SESSION["body_colour"] ?> >

IE6 Session Problem

When you click your back button to make changes in the form, you have to click the REFRESH button on that page to get the information that you posted back into the form. This only works about 50% of the time. The other 50% the users information is lost. This can be horrific for users… but  there is a simple solution. Enter this right below the session_start() of each script:

header(“Cache-control: private”);

Discussion of Prefs

Now this is all great at the moment but we do have a problem – a session automatically closes when a user shuts his web browser. If that person has spent hours setting all their user preferences and they disappear when the browser is closed you aren’t going to get many repeat users. So while sessions maintain state over a visit we need someway of storing data between visits. One solution is to store such valuable user preferences in the  database for repeated users. And when these users come again to visit your site, simply fetch these values from database and assign them to session variables.

Redirection

Just like Cookies and Sessions, you MUST call the header() function before anything is output to your web browser. Otherwise you will get a famous error message i.e. Headers already sent etc.

<?php
    header(“Location: http://www.example.com/”);
?>
Similarly,
<?php
    header(“Location: myApp/login.php”);
?>

Web Mail Systems

Its easy to send emails in php too. Mail() function uses SMTP (Simple Mail Transfer Protocol) to send emails automatically from inside your scripts. To receive and process mail PHP can use the IMAP protocols (we won’t go into this). PHP comes with the IMAP library and this can be used for POP and NNTP (news) connections.

<?php
$email   = "lucky@sourcecodemania.com";
$title   = "More SPAM!";
$message = "This is my first\n PHP mail message";
$from    = "From: falak@msn.com\n";
mail($email, $title, $message, $from);
?>

That’s it for today!  :-) Shoot your questions!

Next >> Lecture 9. AJAX and PHP

Tagged with: PHP
 

2 Responses to 8. Sessions in PHP

  1. Falak says:

    nice topic

  2. Dave Cleal says:

    Bit late, but perhaps worth pointing out that sessions use cookies, and so don’t fix problems you might have with cookies: they just provide some convenience. Also the mad ‘30% of web cookies are unreliable” is (i) mad and (ii) if it were true, using sessions wouldn’t help.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 

Looking for something?

Use the form below to search the site:


Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds

Set your Twitter account name in your settings to use the TwitterBar Section.