Sessions

Contact Us or call 1-877-932-8228
Sessions

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();
?>

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().
Next