Beware using the IP address as a unique token for a session. Any users that go through a proxy will appear to come from the same IP. AOL users for instance rotate through a handful of IP addresses for each request.
The other replies have hopefully pointed you in the right direction.
Also, if you decide to store the information in a file make sure you lock it when updating and reading. Otherwise it will get corrupted at some point.
Updated: I had a chance to look at how I had coded the login stuff on my pages here. The relevant bit is to use Apache::Session which gives me an ID that I then stuff into a cookie. The IDs generated are relatively secure, they use all sorts of good random info then run it through an MD5 hash so I think they are unguessable. Anyway, onto the code:
use Apache::Session::File;
use CGI::Cookie;
use constant TIMEOUT => 60 * 60 * 2; # 2 hours
use constant COOKIE_NAME => 'MY_COOKIE';
use constant BASE_URL => '/';
# Get the ID from the cookie (if one was set)
my $raw_cookie = $r->header_in('Cookie') || "";
my %cookies = parse CGI::Cookie($cookie);
my $id = $cookies{COOKIE_NAME};
# Get the session object from disk
my %session;
tie %session, 'Apache::Session::File, $id, {
Directory => '/tmp/state',
LockDirectory => '/tmp/state',
};
# Set the cookie back if it was new
if (not defined $id) {
my $new_cookie =
new CGI::Cookie(-name => COOKIE_NAME,
-value => $session->{_session_id},
-path => BASE_URL,
);
$r->err_header_out('Set-Cookie' => $new_cookie);
}
# Now just read and write things to the session object
# and they will get saved. You have to be careful about
# any references though. See the docs for details.
# Check to make sure the session is valid
my $cur_time = time;
unless (defined $session{last_access} and
$session{last_access} < time - TIMEOUT and
defined $session{valid} and
$session{valid} == 1)
{
# Illegal access, bump to the login page
# It must make the session valid by setting the
# last_access and valid fields.
}
$session{last_access} = $cur_time;
Please note that this code will probably need to be changed to fit your web environment. I was using $r since my code comes from mod_perl. If you are using straight CGI then there is a CGI.pm thing to set the cookie stuff in the response header. The above may or may not work since I cut and pasted relevant bits from my setup (I am using Mason) and actually have stuff split up across subroutines because my data store and autentication is a bit more twisty.
-ben |