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.

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.

To continue to learn PHP go to the top of this page and click on the next lesson in this PHP Tutorial's Table of Contents.

Use of this website implies agreement to the following:

Copyright Information

All pages and graphics on this Web site are the property of Webucator, Inc. unless otherwise specified.

None of the content on this website may be redistributed or reproduced in any way, shape, or form without written permission from Webucator, Inc.

No Printing or saving of web pages

This content may not be printed or saved. It is for online use only.


Linking to this website

You may link to any of the pages on this website; however, you may not include the content in a frame or iframe without written permission from Webucator, Inc.


Warranties

This website is provided without warranty of any kind. There are no guarantees that use of the site will not be subject to interruptions. All direct or indirect risk related to use of the site is borne entirely by the user. All code and explanations provided on this site are provided without warranties to correctness, performance, fitness, merchantability, and/or any other warranty (whether expressed or implied).

For individual private use only

You agree not to use this online manual to deliver or receive training. If you are delivering or attending a class that is making use of this online manual, you are in violation of our terms of service. Please report any abuse to courseware@webucator.com. If you would like to deliver or receive training using this manual, please fill out the form at http://www.webucator.com/Contact.cfm.