PHP and MySQL Programming/Session Handling

From Wikibooks, open books for an open world
Jump to: navigation, search

HTML and PHP are "stateless" languages. Meaning that they are incapable of retaining a state between pages. To get around this serious limitation, we use sessions. With sessions, session variables are stored in a file on the web server and so are accessible across multiple pages.

Starting a Session[edit]

Before we can start using session variables, we need to start a session. This needs to be done on every page that makes use of session variables. It is important to note that a session must be started before anything is outputted. Here is the code to start a session :

<?php
session_start();
?>

Please make sure that there are NO SPACES before the "<?php" (php starting tag), as that will return errors!

It is worth noting, that the way in which the server distinguishes between multiple sessions being implemented on it simultaneously is by session ID's. When a unique session is created, it is assigned a Session ID, which the browser retains, and is used to let the we server know which session to use.

Writing Session Variables[edit]

Once a session is created, variables may be stored in the $_SESSION[] array variable. Here is an example :

session_start();
$_SESSION['user_name'] = "Administrator";

Retrieving Session Variables[edit]

Once a session is created, and variables are stored, they may be retrieved from the $_SESSION[] array. Here is an example :

session_start();
if (isset($_SESSION['user_name'])){
   $user_name = $_SESSION['user_name'];
   print $user_name;
}

The above example starts a session, then checks if the session variable 'user_name' has been created (with the isset() function), if it has, then it assigns its value to $user_name, and prints it to the screen.

Destroying a Session[edit]

To destroy a session, we use the session_destroy() function. This is useful if we want to, for example, log a user off of a web-application. Thus we would use the following code :

session_start();
session_destroy();

Note that we first need to start the session before we destroy it. This is because the session_destroy() function destroys the currently active session.

Previous: Database Connectivity | TOC | Next: Command-Line Programming