!/usr/bin/perl -w
use strict;
use CGI;
use Apache::Session::MySQL;
use CGI::Carp qw(fatalsToBrowser);
my $q = new CGI;
my $sess_id = $q->cookie(-name=>'sess_id'); # substitute the name of your session cookie here
# These are the parameters for the session
my $params = { DataSource => 'dbi:mysql:sessions',
UserName => 'root',
Password => '',
LockDataSource => 'dbi:mysql:sessions',
LockUserName => 'root',
LockPassword => ''
};
my %session;
# The following lines tie %session to the session data
# The script will die if we give it a $sess_id that doesn't exist.
# So we put the tie call in an eval block. If there's an error
# in $@ then we create a new session.
eval {
tie (%session, 'Apache::Session::MySQL', $sess_id, $params);
};
tie (%session, 'Apache::Session::MySQL', undef, $params) if ( $@ );
if ( $q->param('action') )
{
# We should delete the session.
tied(%session)->delete;
# Even though the session is deleted, the hash is still hanging around.
# So we will just undef it, so that it doesn't confuse the script.
undef %session;
print $q->header;
}
elsif ( my $user = $q->param('username') )
{
# We just created a new session.
$session{'username'} = $user;
# Remember to create the cookie.
my $cookie = $q->cookie(-name=>'sess_id',
-value=>$session{_session_id});
print $q->header(-cookie=>$cookie);
}
else
{
print $q->header;
}
if ( $session{'username'} )
{
# The session already exists. Say hello.
print "Hello $session{'username'}!
";
print "Logout";
}
else
{
# Print login box
print "