Heh, just got done writing this code up for another thread, should fit here too.
There's a couple of ways to check sessions.
My personal favorite (for login scripts and such) is to store the user's information in the session itself when they log in successfully. That way, I can double check it against the database if I'm paranoid.
Again, the below example is for a page that requires users to be "logged in". It checks to see if a certain session variable ("logged_in") is set. If it is, it checks the rest of the information against the database (not needed, but makes it slightly more secure). If that passes, it displays the content a logged in user should see. If it fails or if the session variable isn't set, it shows the content a non-logged in user should see (usually a login form).
When the user logs in, it stores a bunch of session variables with information gathered from the database:
- "logged_id" = The userid (in my database) of the user.
- "logged_name" = The username they are logged in as.
- "logged_pass" = The md5 encrypted password for the user.
- "logged_in" = A flag. Either "yes" or "no".
Now, say someone logs in successfully and then visits a page that will have different content based on whether or not you they are logged in:
private.php:
session_start();
/* DATABASE VARIABLES */
$db = array (
"server" => "localhost",
"username" => "username",
"pass" => "password",
"db" => "database_name"
);
$dbconnect = mysql_pconnect($db["server"], $db["username"], $db["pass"]);
mysql_select_db($db["db"]);
/* Check to see if user has a session active.
If so, double check the registered session
variables against the database, cuz I'm paranoid. ;) */
if ($_SESSION["logged_in"] == "yes")
{
$query = "select * from users where username = '".$_SESSION["logged_name"]."'
&& password = '".$_SESSION["logged_pass"]."'";
$result = mysql_query($query, $dbconnect);
$valid_user = mysql_num_rows($result);
if ($valid_user != 1)
{
/* User has a session set, but the information stored in it
does not match with the database. Probably a lame
hacking attempt. Give em the "not logged in" content.
and/or login form. */
}
else
{
/* User has a session set and the information stored within
it DOES match the database. This is a valid user. Give
them the content valid users should see. */
}
}
else
{
/* User does not have a session established. Show them the
"not logged in" content and/or a login form. */
}
In the above example, one script can show two completely different results. This way if a valid user (one who has a session active) bookmarks the page, the next time they visit that page it will check for the valid session again. If the user has closed their browser since the bookmarking, the session has been destroyed and the page will display the "not logged in" content.
I hope that's what you were asking. Of course If it wasn't feel free to ask some more!