Understanding PHP Sessions

From Techotopia
Revision as of 16:57, 6 June 2007 by Neil (Talk | contribs) (New page: In the previous chapter (PHP and Cookies - Creating, Reading and Writing) we looked at the use of cookies to maintain state. In that chapter we also mentioned the use of PHP seesions a...)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

In the previous chapter (PHP and Cookies - Creating, Reading and Writing) we looked at the use of cookies to maintain state. In that chapter we also mentioned the use of PHP seesions as an alternative to the use of cookies. We also provided an overview of the difference between cookies and PHP sessions.

In this chapter we will explore the concept of PHP sessions in more detail and provide some examples of how to create and use session.

What is a PHP Session?

PHP Sessions allow web pages to be treated as a group, allowing variables to be shared betweem different pages. One of the weaknesses of cookies is that the cookie is stored on the user's computer (by user we mean the person with the browser visiting your web site). This provides the user the ability to access, view and modify that cookie for potentially nefarious purposes. PHP sessions, on the other hand, store only an ID cookie on the users system which is used to reference the session file on the server. As such, the user has no access to the content of the session file thereby providing a secure alternative to cookies. PHP sessions also work when the user has disabled the browser's cookie support. In this situation it includes the session ID information in the web page URLs.

Creating a PHP Session

PHP sessions are created using the session_start() function and should the first function call of the PHP script on your web page (i.e before any output is written to the output stream).

The following example demonstrates the creation of a PHP session:

<?php
       start_session();
?>
<html>
<head>
<title>A PHP Session Example</title>
</head>
<body>
</body>
</html>

Creating PHP Session Variables

Variables can be assigned to a session using the $_SESSION array. This is a global array that is accessible to all the pages on your web site. The is an associative array (see PHP Arrays for details of using arrays in PHP) and as such it is possible to access array elements using the variable name as an index.