class_session.php
Author: Troy Wolf (troy@troywolf.com)
Modified Date: 2005-06-18 14:20
Download: class_session.zip
View class source: class_session.php source
class_session is a session management and password protection class.
It can be used to perform 2 major functions:
- Create and maintain session state between page hits.
The class does this using simple session cache files
into which the session is stored as a serialized array.
This is similar to how PHP's built-in sessions store
session data. One big advantage of this class is that
you have full control over the session timeout.
- Password protect PHP pages by requiring authentication.
Simply pass in "true" when creating a new session
object to use this functionality. You'll also need to
create your own login.php script. A sample login.php
is packaged with this class.
This is accomplished by storing a single session id cookie on the user's
computer. No other data is stored on the user's computer, and the cookie
expires when the user closes their browser. Because PHP can't write cookies
after browser output is started, make sure you create the session and save
session data BEFORE you start any browser output.
Before you can use the class, you need to modify the 'dir' property in the
class file to point to a directory where you want to store session cache
files. You'll find this property in the session() function (the class
constructor).
/*
Define the directory to save session files in. This defaults to the current
dir, but this is probably not what you want. For one thing, it is INSECURE!
It also will prevent your sessions from working between scripts in different
dirs. It is highly recommended that you set this to a non web-accessible
dir. End this value with a "/".
*/
$this->dir = realpath("./")."/";
To use the class in your scripts, you first need to include the class file.
/*
Include the class. Modify path according to where you put the class file.
*/
require_once(dirname(__FILE__).'/class_session.php');
Next, you instantiate the session object. Do this in every page you want to
either save or restore the session in. (Or password-protect, but we'll talk
more about that later.) The code example below also shows how to echo the
session's 'log' property which will tell you about what's wrong if things
don't work. NOTE: Create your session and save any session data BEFORE you
start any browser output, or this will not work.
/*
Instantiate a new session object. If session exists, it will be restored,
otherwise, a new session will be created--placing a sid cookie on the user's
computer.
*/
if (!$s = new session()) {
/*
There is a problem with the session! The class has a 'log' property that
contains a log of events. This log is useful for testing and debugging.
*/
echo "<h2>There is a problem with the session!</h2>";
echo $s->log;
exit();
}
Now that you have a session, you can save data in it. Suppose the user
submitted a form to your script with their name and favorite color. Again, we
want to test if anything fails. If the save() method returns false, we'll
look at the session's 'log' property.
$s->data['uname'] = $_POST['uname'];
$s->data['favcolor'] = $_POST['favcolor'];
$s->data['ip_address'] = $_SERVER['REMOTE_ADDR'];
if (!$s->save()) {
/*
There is a problem with the session! The class has a 'log' property that
contains a log of events. This log is useful for testing and debugging.
*/
echo "<h2>There is a problem with the session!</h2>";
echo $s->log;
exit();
}
If everything worked, there will be a SID (session ID) cookie on the user's
computer and a session cache file on your webserver's hard drive with the same
name as the SID.
Now you have a way to maintain state specific to this user. You can access
this session data in all the rest of your scripts. With the class, you don't
do anything special to restore the session--simply create a new session
object, and if a session exists, it will be restored. Here is a complete
code example showing a script that restores a previously created session and
uses the session data.
<?php
/*
Include the class. Modify path according to where you put the class file.
*/
require_once(dirname(__FILE__).'/class_session.php');
/*
Instantiate a new session object. If session exists, it will be restored,
otherwise, a new session will be created--placing a sid cookie on the user's
computer.
*/
if (!$s = new session()) {
/*
There is a problem with the session! The class has a 'log' property that
contains a log of events. This log is useful for testing and debugging.
*/
echo "<h2>There is a problem with the session!</h2>";
echo $s->log;
exit();
}
?>
<html>
<body>
Hello, <?= $s->data['uname'] ?>! Your favorite color is
<?= $s->data['favcolor'] ?>.
<br /><br />
Your IP Address is <?= $s->data['ip_address'] ?>.
</body>
</html>
The class also provides an expire() method to end the session. You can use
this with a "logout" feature.
/*
Expire the session which clears the session data, deletes the
session cache file from your web server's hard drive, and expires the SID
cookie on the user's computer.
*/
$s->expire();
View the source for the example logout.php.
Hopefully you now understand how easy it is to use class_session to maintain
user data between pages.
View the source for example.php which puts this
all together for you, and is included in the download.
Using class_session to password-protect PHP pages.
Another powerful feature of session_class is the ability to password-protect
pages. The class uses a session variable 'logged_in' to keep track of whether
the user is logged in or not. So, let's walk through how to use this
functionality.
Instantiate the object like before, but this time, pass 'true' to the
constructor. The class will then test the 'logged_in' session variable. If it
is false, it will "remember" where the user was going, then redirect to your
login page.
/*
Instantiate a new session object. If session exists, it will be restored,
otherwise, a new session will be created--placing a sid cookie on the user's
computer. Passing in "true" tells class_session to require login before
allowing access to this page. Read the comments in class_session.php and
login.php about setting up your own authentication.
*/
if (!$s = new session(true)) {
/*
There is a problem with the session! The class has a 'log' property that
contains a log of events. This log is useful for testing and debugging.
*/
echo "<h2>There is a problem with the session!</h2>";
echo $s->log;
exit();
}
So, if the user hit your page and was not logged in, they would be directed to
your login page. This can be any page you want--you define this in the class
by setting the 'login_page' property in the session() function. It defaults to
login.php. An example login.php is included in the download. You can modify
this login.php or create your own, but there are a few pieces in it that you
must keep to make it work with class_session. You can
view the source of login.php.
Remember, you can use the expire() method to end the session--which
effectively logs the user out. Alternatively, if you wanted to continue to
maintain the session, but only log the user out from access to protected
content, you can just set the 'logged_in' session variable to false.
/*
If you you want to maintain the session, but you want to remove the "logged in"
status from the session, just do this.
*/
$s->data['logged_in'] = false;
$s->save();
About the author
Troy Wolf operates
ShinySolutions Webhosting,
and is the author of
SnippetEdit--a PHP application
providing browser-based website editing that even non-technical people can
use. Website editing as easy as it gets. Troy has been a professional
Internet and database application developer for over 12 years. He has many
years' experience with ASP, VBScript, PHP, Javascript, DHTML, CSS, SQL, and
XML on Windows and Linux platforms. Check out
Troy's Code Library.