Session Control and Cookies

Session Control and Cookies

In this lesson of the PHP tutorial, you will learn… 

  1. To maintain sessions to track user visits.
  2. To write and read cookies.

In the lesson on authenticaion, we created a login form and learned to authenticate users by comparing their emails and passwords to records in a database. In this lesson, we will use session variables to remember that the users are logged in as they go from page to page and we will use cookies to make it easier for users to log in on future visits.

Sessions

A session begins when a visiting client somehow identifies itself to the web server. The web server assigns the client a unique session id, which the client uses to re-identify itself as it moves from page to page on the website. Most of the time, these unique ids are stored in session cookies that expire after the client hasn’t interacted with the server for some amount of time. The amount of time varies depending on the web application. For example, an online investment site might have very short sessions, so that if a user leaves her computer without logging out, another user who sits down at the same computer several minutes later cannot continue with the first user’s session.

Configuring Sessions

In PHP, session management is configured in the php.ini file. To have a user’s session start as soon as the user visits the website, the session.auto_start flag must be set to 1.

The session length is also set in the php.ini file with the session.gc_maxlifetime variable. The default value is 1440 seconds (24 minutes).

Session Functions

The following table shows the most common session functions.

Function Explanation
session_start() Starts new session if one does not exist. Continues current session if one exists.
session_unset() Unsets all session variables.
session_destroy() Kills session.

Together, the files below illustrate how sessions can be tracked.

Code Sample: Sessions/Demos/Session1.php

<?php
//Begin a session and create a session variable in
//the $_SESSION array.
 session_start();

 $_SESSION['Greeting'] = 'Hello world!';

 echo $_SESSION['Greeting'];
?>
<hr/>
<a href="Session2.php">Next page</a>

Code Sample: Sessions/Demos/Session2.php

<?php
//Continue session, show that session variable still
//exists and then unset the session variable
 session_start();

 echo $_SESSION['Greeting'];

 unset($_SESSION['Greeting']);
?>
<a href="Session3.php">Next page</a>

Code Sample: Sessions/Demos/Session3.php

<?php
//Continue session, show that session variable no longer
//exists and then kill session.
 session_start();

 echo $_SESSION['Greeting'];

 session_unset();
 session_destroy();
?>
Code Explanation

The code above illustrates the following points.

  • Pages that are part of the session should begin with a call to session_start().
  • Session variables are created in the $_SESSION array.
  • Session variables are deleted in the same way as other variables – using the unset() function.
  • All session variables can be unset with the session_unset() function. This should be called before calling session_destroy().
  • Sessions are killed with a call to session_destroy().

Cookies

Cookies are stored in text files that sit on the client machine. Web pages with the right permissions can read from and write to cookies. They are generally used to track user information between visits.

In PHP, cookies are set with the setcookie() function, which can take several parameters including:

  • The cookie’s name (required).
  • The cookie’s value.
  • The cookie’s expiration date (if this isn’t set, the cookie will expire when the browser window is closed).
  • The directory path on the server that can read the cookie.
  • The domain name that can read the cookie.
  • A flag indicating whether the cookie should only be read over https.

The following code will set a cookie that expires in one week.

setcookie('flavor','chocolate chip', time()+60*60*24*7);

There is no deletecookie() function. To delete a cookie, set the expiration date to sometime in the past, like this.

setcookie('flavor','chocolate chip', time()-10000);

Cookies are set in the HTTP header, so they must be set before any HTML code is passed back to the browser.

Exercise: Authentication with Session Control

Duration: 30 to 40 minutes.

In this exercise, you will create a login form that allows a user to log in to a site, rather than just a page on the site. You will also modify several other pages so that their content changes based on whether or not the user is logged in.

  1. Open Sessions/Exercises/index.php in your editor. This file has been completed for you. Note the following:
    • At the top of the document, we start a session with session_start().
    • We’ve added an outer if condition to the body to check if EmployeeID already exists in the $_SESSION array. If it does, this means the user has already logged in.
               if (array_key_exists('EmployeeID',$_SESSION))
      {
       echo '<div align="center">
         Logged in as ' .
         $_SESSION['FirstName'] . ' ' .
         $_SESSION['LastName'] .
         '</div>';
      }
      else
      {
       if (array_key_exists('LoggingIn',$_POST))
       {
        require 'Includes/Login.php';
       }
       if (!array_key_exists('LoggingIn',$_POST))
       {
        require 'Includes/LoginForm.php';
       }
       if (strlen($msg) > 0)
       {
        echo "<div align='center'>$msg</div>";
       }
      }
  2. Open Sessions/Exercises/Includes/Login.php (you can use LoginPear.php if you prefer) in your editor. Modify the code, so that when the user logs in, she is remembered for the duration of her visit. You should remember her first name, last name and employee id.
  3. Sessions/Exercises/Includes/Footer.php has been changed to include a “Log out” link, which points to Sessions/Exercises/Logout.php. Open Sessions/Exercises/Logout.php in your editor. Add code to log the user out (i.e, delete all session variables and kill the session).
  4. Open Sessions/Exercises/OtherPage.php in your editor. Notice that it includes Includes/LoginCheck.php.
  5. Open Sessions/Exercises/Includes/LoginCheck.php in your editor. You will see that it currently contains code to redirect the page to index.php. Modify this script so that it only redirects to index.php if the user is not logged in.

Write code so that the user can indicate that she would like to be remembered between visits. If she chooses to be remembered, she should not have to log in again for a week. You will need to modify index.php, Includes/LoginForm.php, Includes/Login.php and Includes/Logout.php. You may also find it useful to create a new include file (e.g, CookieCheck.php) to hold the code that checks for the cookie.

Session Control and Cookies Conclusion

Session management is a key aspect necessary to create “web applications” from sets of web pages. In this lesson, you have learned to use session variables to create site-wide user authentication and cookies to remember visitors between visits.

Advertisements

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