What will probably be the easiest thing to do (what i do 😉) Is to create your session when they log in, and on each page, include an authentication file up the top, so that if they aren't log in, it just redirects them to the login page.
Login page:
<?php
if(isset($_SESSION['username'])) {
// They are already logged in, so redirect them to the index.php
header("Location: index.php");
// We put the exit in so that just in case it doesn't redirect,
// it's still gonna stop processing.
exit;
} else {
if(isset($_POST['submit'])) {
// They have submitted the form, so do your validation (simplified for demo purposes)
$sql = "SELECT id, username FROM users ";
$sql .= "WHERE username='".$_POST['username']."' AND password='".$_POST['password']."'";
// Include the database connect from BELOW your web root
include '../inc/dbconnect.inc.php';
$result = mysql_query($sql, $db) or die("Could not perform query! MySQL said: ".mysql_error());
if(mysql_num_rows($result) > 0) {
// Get your data into an associative array
$user_data = mysql_fetch_assoc($result);
// Start your session
session_start();
/* Set your session data. This loops through all of the keys in your data
array, and sets them to a corresponding session variable.
eg. $user_data['id'] = $_SESSION['id'];
This just makes it easier to code, because you should only be getting the
data you need from the query anyway ;)
*/
foreach($user_data as $k=>$v) {
$_SESSION[$k] = $v;
}
// The user has been validated, and session data applied,
// so redirect them to the index
header("Location: index.php");
exit;
} else {
// Ack, wrong user or password!
echo "Invalid Username/Password";
}
}
echo "<form method=\"post\" action=\"".$_SERVER['PHP_SELF']."\">";
echo "<br /><input type=\"text\" name=\"username\" />";
echo "<br /><input type=\"password\" name=\"password\" />";
echo "<br /><input type=\"submit\" name=\"submit\" value=\"Login\" />";
}
?>
And now, the included file (auth.inc.php)
<?php
session_start();
if(!isset($_SESSION['username'])) {
header("Location: /login.php");
exit;
}
?>
That was quite easy, wasn't it? And then in the top of all your files, you just:
include_once("/../inc/auth.inc.php");
Hope that helps 🙂