[英]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. 当用户成功通过身份验证后,如果用户尚未注册参加培训,则会将其重定向到register.php。
If the user has already signed up for training, s/he is redirected to registered.php to view/modify his or her training classes. 如果用户已经注册了培训,他/她将被重定向到registered.php以查看/修改他或她的培训课程。
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. 问题是如果用户试图直接进入register.php或registered.php,他/她进入任何网页而不先登录。
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 //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:- 有2个错误: -
In login.php
start the session using session_start();
在login.php
使用session_start();
启动会话session_start();
at the top of the script, so that the code that sets variables in $_SESSION
will work. 在脚本的顶部,以便在$_SESSION
中设置变量的代码将起作用。
In register.php
change the IF statement from 在register.php
更改IF语句
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'])
那么IF不会测试$_SESSION['loggedin'] != true
如果IF的第一部分发现变量不存在,则为$_SESSION['loggedin'] != true
即!isset($_SESSION['loggedin'])
On login.php have session_start();
在login.php上有session_start();
somewhere on the top. 顶部的某个地方。
On each script that you use the session you must have it. 在您使用会话的每个脚本上,您必须拥有它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.