PHP Starting & Storing a Session

Posted by tutor | Posted in PHP Tutorial | Posted on 15-12-2009-05-2008

0

Whenever a user logs in to a system some variables are set to identify this same user throughout his working duration and when the user logs out of the system the variables are reset. This duration from log=in to log-out is called a session and the variables used are session variables to identify a session.

Starting a PHP Session

Before storing the user information in a session, it should be first started. The code to start a session must be at the very beginning of your code, before any HTML or text is sent.

    <?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

When you want to store user data in a session use the built-in PHP associative array $_SESSION. This is where you both store and retrieve session data. In previous versions of PHP there were other ways to perform this store operation, but it has been updated and this is the correct way to do it.

    <?php
    session_start();
    // store session data
    $_SESSION['username']=”Tutor”;
    ?>
    <html>
    <body>
    <?php
    //retrieve session data
    echo “Username=”. $_SESSION['username'];
    ?>
    </body>
    </html>
    Output:

    Username=Tutor

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:

    <?php
    session_start();
    if(isset($_SESSION['views']))
    $_SESSION['views']=$_SESSION['views']+1;
    else
    $_SESSION['views']=1;
    echo “Views=”. $_SESSION['views'];
    ?>

Write a comment

Twitter Users
Enter your personal information in the form or sign in with your Twitter account by clicking the button below.