简体   繁体   中英

I am getting Notice: Undefined index: loggedin in when using SESSION

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";
}

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 ie !isset($_SESSION['loggedin'])

On login.php have session_start(); somewhere on the top.

On each script that you use the session you must have it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM