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.
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
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).
The following table shows the most common session functions.
||Starts new session if one does not exist. Continues current session if one exists.|
||Unsets all session variables.|
Together, the files below illustrate how sessions can be tracked.
<?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>
<?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>
<?php //Continue session, show that session variable no longer //exists and then kill session. session_start(); echo $_SESSION['Greeting']; session_unset(); session_destroy(); ?>
The code above illustrates the following points.
session_unset()function. This should be called before calling