这是我的登录代码:
<!DOCTYPE = html>
<html lang="nl">
<head>
<title>
Bioscoop
</title>
<link rel="stylesheet" href="css/style.css"/>
<?php
include('config.php');
?>
</head>
<body>
<?php
if(isset($_POST["login"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
{
$message = '<label>Vul alle velden in</label>';
}
else
{
$query = "SELECT * FROM admins WHERE username = :username AND password = :password";
$statement = $con->prepare($query);
$statement->execute(
array(
'username' => htmlspecialchars($_POST["username"]),
'password' => htmlspecialchars($_POST["password"])
)
);
$count = $statement->rowCount();
if($count > 0)
{
$_SESSION["username"] = $_POST["username"];
$username = $_SESSION["username"];
$query = "SELECT rol FROM admins WHERE username = :username";
$stm = $con->prepare($query);
$stm->bindParam(':username', $username, PDO::PARAM_STR, 20);
$stm->execute();
$result = $stm->fetchAll(PDO::FETCH_OBJ);
foreach ($result as $pers) {
$rol = $pers->rol;
$_SESSION["rol"] = $rol;
if($_SESSION["rol"] == 'admin') {
header("location:logged.php");
} else {
header("location:login.php");
}
}
}
else
{
$message = '<label>Verkeerde Gegevens</label>';
}
}
}
?>
<header class = "head">
<img id = "hoofdlogo" src = "img/cinema.png" alt="Logo cinema">
<p id="copyright">©JopRill</p>
</header>
<nav>
<ul>
<li><p><a href="index.php"> Home </a></p></li>
<li><p><a href="films.php"> Films </a></p></li>
<li><p><a href="#"> Login </a></p></li>
</ul>
</nav>
<form method="post">
<div class="form" >
<div id="num1"><h2>Login</h2></div>
<label><p>Gebruikersnaam</p></label>
<input type="text" name="username" id="ContactName" value=""/>
<label><p>Wachtwoord</p></label>
<input type="password" name="password" id="ContactEmail" value="" />
<p></p>
<input type="submit" name="login" id="submit" value="Login" />
<?php
if(isset($message))
{
echo '<label class="text-danger">'.$message.'</label>';
}
?>
</div>
</form>
</body>
</html>
这是我登录的页面代码:
<?php
session_start();
?>
<!DOCTYPE = html>
<html lang="nl">
<head>
<title>
Bioscoop
</title>
<link rel="stylesheet" href="css/style.css"/>
</head>
<body>
<?php
include('config.php');
?>
<header class = "head">
<img id = "hoofdlogo" src = "img/cinema.png" alt="Logo cinema">
<p id="copyright">©JopRill</p>
</header>
<nav>
<ul>
<li><p><a href="logout.php"> Logout </a></p></li>
</ul>
</nav>
<?php echo $_SESSION["rol"]; ?>
</body>
</html>
在登录页面代码中,我将“ rol”保存到会话中。这似乎行得通,因为当我单击登录时,我被重定向到Logged.php页面,但是当我尝试回显与登录时相同的会话变量时,它表示未定义。是什么原因造成的?
答案 0 :(得分:0)
要处理$_SESSION
变量,您总是需要以session_start();
开始会话
访问您网站的访问者被分配一个唯一的ID,即 所谓的会话ID。这要么存储在用户的Cookie中 或在网址中传播。
会话支持使您可以在请求之间存储数据 $ _SESSION超全局数组。当访问者访问您的网站时,PHP 将自动检查(如果session.auto_start设置为1)或 您的请求(明确地通过 session_start())是否 会话ID已与请求一起发送。如果是这种情况, 重新创建先前保存的环境。
答案 1 :(得分:-1)
只需添加session_start();在第一个文件中...