Reputation: 649
When a user is successfully authenticated, s/he is either redirected to register.php if the user has not yet signed up for training.
If the user has already signed up for training, s/he is redirected to registered.php to view/modify his or her training classes.
So far, this works fine.
Problem is if user attempts to go directly to register.php or registered.php, s/he gets into any of the web pages without logging in first.
This is what I am trying to prevent but I keep getting the following error message:
Notice: Undefined index: loggedin in .... on line 3
Please log in first to see this page
Here is what I am using so far and thanks for your help.
//login.php
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);
// hash to sanitize the input further
$pass = md5($pass);
$tSQL = "SELECT u.empl_first, u.username FROM users u inner join Training t on u.Employee_Id = t.Employee_ID WHERE USERNAME = ?
and PASSWORD = ? ";
$params = array($user, $pass, $params);
$sqll = sqlsrv_query($con, $tSQL);
if ($objResult = sqlsrv_fetch_array($sqll, SQLSRV_FETCH_ASSOC)) {
$firstname = $objResult["empl_first"];
$_SESSION["firstname"] = $objResult["empl_first"];
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $user;
header('location:registered.php');
}
else
header("location:register.php?user='".ms_escape_string($user)."'&pass='".ms_escape_string($pass)."' ");
sqlsrv_close($con);
?>
//register.php
<?php
session_start();
if (!isset($_SESSION['loggedin']) && $_SESSION['loggedin'] != true) {
echo "Please log in first to see this page";
}
Upvotes: 2
Views: 2208
Reputation: 94662
There are 2 mistakes:-
In login.php
start the session using session_start();
at the top of the script, so that the code that sets variables in $_SESSION
will work.
In register.php
change the IF statement from
if (!isset($_SESSION['loggedin']) && $_SESSION['loggedin'] != true)
To
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] != true)
then the IF will not test $_SESSION['loggedin'] != true
if the variable is found to not exist by the first part of the IF i.e. !isset($_SESSION['loggedin'])
Upvotes: 3
Reputation: 395
On login.php have session_start();
somewhere on the top.
On each script that you use the session you must have it.
Upvotes: 0