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.
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 startedbefore anything is outputted. Here is the code to start a session:
<?phpsession_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 web server know which session to use.
Once a session is created, variables may be stored in the$_SESSION[] array variable. Here is an example:
session_start();$_SESSION['user_name']="Administration";
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 theisset() function), if it has, then it assigns its value to$user_name, and prints it to the screen.
To destroy a session, we use thesession_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 thesession_destroy() function destroys the currently active session.
| PHP and MySQL Programming Session Handling | Command Line Programming |