Logo         Community
The Company
Your Account
Contact Us
PHP 101 (part 10): A Session In The Cookie Jar
Use sessions and cookies to track visitors to your site.

| Remember Me |

Here's another example, this one asking you to log in and then storing your login name and session start time as two session variables. This information is then used to display the total number of minutes the session has been active.

// initialize a session

if (!isset($_SESSION['name']) && !isset($_POST['name'])) {
    // if no data, print the form
    <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
        <input type="text" name="name">
        <input type="submit" name="submit" value="Enter your name">
else if (!isset($_SESSION['name']) && isset($_POST['name'])) {
    // if a session does not exist but the form has been submitted
    // check to see if the form has all required values
    // create a new session
    if (!empty($_POST['name'])) {
        $_SESSION['name'] = $_POST['name'];
        $_SESSION['start'] = time();
        echo "Welcome, " . $_POST['name'] . ". A new session has been activated for you. Click <a href=" . $_SERVER['PHP_SELF'] . ">here</a> to refresh the page.";
    else {
        echo "ERROR: Please enter your name!";
else if (isset($_SESSION['name'])) {
    // if a previous session exists
    // calculate elapsed time since session start and now
    echo "Welcome back, " . $_SESSION['name'] . ". This session was activated " . round((time() - $_SESSION['start']) / 60) . " minute(s) ago. Click <a href=" . $_SERVER['PHP_SELF'] . ">here</a> to refresh the page.";

In this example, the presence or absence of a session variable is used to decide which of the three possible screens to display. The session start time is also recorded in $_SESSION['start'] with the time() function, which returns the total number of seconds between January 1 1970 and the current time. At a later stage, the value stored in $_SESSION['start'] is compared with the most current value of time() to calculate and display an (approximate) display of elapsed time.

It's important to note that the call to session_start() must appear first, before any output is generated by the script (assuming you're not using PHP's output buffering feature, which you can read about at http://www.php.net/manual/en/ref.outcontrol.php). This is because the PHP session handler internally uses in-memory cookies to store session data, and the cookie creation headers must be transmitted to the client browser before any output. If you ever see an error like this in one of your session-enabled pages:

''.preg_replace(array('/  /', '/ /'), array('  ', '   '), '
Warning: Cannot send session cache limiter - headers already sent (output started at ...)

it's usually because somewhere, somehow, some output has found its way to the browser before session_start() was called. Even a carriage return or a blank space outside the PHP tags surrounding session_start() can cause this error, so watch out for them.

As noted previously, every session has a unique session ID, which PHP uses to keep track of different clients. This session ID is a long alphanumeric string, which is automatically passed by PHP from page to page so that the continuity of the session is maintained. To see what it looks like, use the session_id() function, as in this simple example:

// initialize a session

// print session ID
echo "I'm tracking you with session ID " . session_id();

When the user shuts down the client browser and destroys the session, the $_SESSION array will be flushed of all session variables. You can also explicitly destroy a session - for example, when a user logs out - by calling the session_destroy() function, as in the following example:

// initialize a session

// then destroy it

In case you were wondering if you read that right - yes, before you can call session_destroy() to destroy a session, you must first call session_start() to recreate it.

Remember that $_SESSION is a superglobal, so you can use it inside and outside functions without needing to declare it as global first. The following simple example illustrates this:

// initialize a session

// this function checks the value of a session variable
// and returns true or false
function isAdmin() {
    if ($_SESSION['name'] == 'admin') {
        return true;
    else {
        return false;

// set a value for $_SESSION['name']
$_SESSION['name'] = "guessme";
// call a function which uses a session variable
// returns false here
echo isAdmin()."<br />";

// set a new value for $_SESSION['name']
$_SESSION['name'] = "admin";
// call a function which uses a session variable
// returns true here
echo isAdmin()."<br />";

You can read more about sessions and session handling functions at http://www.php.net/manual/en/ref.session.php.

How to do Everything with PHP & MySQL
How to do Everything with PHP & MySQL, the best-selling book by Melonfire, explains how to take full advantage of PHP's built-in support for MySQL and link the results of database queries to Web pages. You'll get full details on PHP programming and MySQL database development, and then you'll learn to use these two cutting-edge technologies together. Easy-to-follow sample applications include a PHP online shopping cart, a MySQL order tracking system, and a PHP/MySQL news publishing system.

Read more, or grab your copy now!

previous page more like this  print this article  next page
In trog...
Logging With PHP
Building A Quick-And-Dirty PHP/MySQL Publishing System
Output Buffering With PHP
Date/Time Processing With PHP
Creating Web Calendars With The PEAR Calendar Class
In the hitg report...
Crime Scenes
Animal Attraction
Lord Of The Strings
In boombox...
Patience - George Michael
Think Tank - Blur
My Private Nation - Train
In colophon...
Hostage - Robert Crais
The Dead Heart - Douglas Kennedy
Right As Rain - George Pelecanos
In cut!...
American Chai
The Core
Find out how you can use this article on your own Web site!

Copyright © 1998-2018 Melonfire. All rights reserved
Terms and Conditions | Feedback