Things You'll Need:
- PHP enabled web server
-
Step 1
Page 1 – The Log-In Page:
Each page that wants to access the $_SESSION variables will need to issue the command session_start(). You must issue this command prior to any output to the browser. This will allow the server to track the user’s visit automatically.
After session_start() is issued, we test if the UserName session variable already exists by using the isset() function. If it does exist, we transfer the user to page 3 using JavaScript. If it does not exist, we display a form with a textbox and submit button. In your application, you will probably want to include a textbox to capture the password. -
Step 2
Page 2 – The Log-In Processing Page:
The second page repeats the first in that it starts the session (it is not actually starting a brand new session, but retrieving the session started on the first page). It then transfers the user to page 3 if they have already logged in.
If the session variable UserName is not set (i.e. does not exist), it compares what they typed into the UserName textbox on page 1 ($_GET['UserName'] ) with a known value ("kalel"). You would usually access a database at this point, but for this example I limited it to a particular string.
If the values match, we set the session variable ($_SESSION['UserName'] = $_GET['UserName']; ) and take them to page 3. If the values do not match, we display an error and send them back to page 1. -
Step 3
Page 3 – The Main Page:
The main page starts a session and then tests for the existence of the UserName session variable. If it does not exist, the user is driven to the log in page. If it does exist, the main page is displayed. -
Step 4
Note: I added an exit() command after each JavaScript redirect just to make sure that all non-relevant output is skipped. Probably not worth it, but it makes me feel better.
Also, if you want to see the actual session identifier being used, just add this to any page:
echo session_id();
And finally, if you want to clear the session and all of its variables, use these commands:
session_unset();
session_destroy();














Comments
lordjeffrey said
on 7/20/2009 I love me some session variables - perhaps too much :) They are incredibly easy to use for sending info back and forth all over the place in a script. But you do have to clean up, and code carefully. Best to keep their use limited to things like this. Good and 'correct' article. 5 stars and a "recommend".