会话变量未被传输

时间:2016-04-17 14:30:53

标签: php mysql session variables authentication

我是学习PHP(作为一种爱好),我想构建一个简单的登录页面来练习。

我有一张表格:

<form action="phpAction/checklogin.php" method="POST">
<p>Username:</p>
<input type="text" name="username">
<p>Password:</p>
<input type="password" name="password">
<br><br>
<input type="submit" value="Submit">
<br><br>
<a href="signup.php">You don't have an account yet?</a>
</form>

发布到php代码:

<?php

// Starts a MySQLi connection to the database
include "../includes/mysqliConn.php";

// Starts a session to keep the user logged in
session_start();

// Posts the username and password from the form and stores it into a session variable

if (isset($_POST["username"]) && isset($_POST["password"])) {
  $_SESSION["username"] = $_POST["username"];
  $_SESSION["password"] = $_POST["password"];
} else {
    die("You cannot be here!");
}
// Checks login
$checklogin = 'SELECT * FROM users WHERE username = $_SESSION["username"] AND password = $_SESSION["password"]';
$result = $conn->query($checklogin);
                if ($result->num_rows = 0){
                    echo "<script language='javascript' type='text/javascript'>alert('Login and/or password wrong!');window.location.href='login.php';</script>";
                    die();
                } else {
                    // Variable to other pages see that the user is logged in
                    $_SESSION["islogged"] = "true";
                    // Redirects to the homepage
                    header("Location: ../index.php");
                }

?>

它将会话变量“islogged”设置为true,以便其他页面可以显示用户的信息。

在网站的标题中我有这个:

<?php

      if ($_SESSION["islogged"] == "true") {
          echo "<a href='#'>Panel</a>";
          echo "<a href='#'>Logout</a>";
      } else {
         echo "<a href='login.php'>Login</a>";
         echo "<a href='#'> / </a>";
         echo "<a href='signup.php'>Sign Up</a>"; 
      }

?>

当变量“islogged”设置为“true”时,页面应显示链接Panel和Logout,而不是Login和Signup。但我一直在登录和注册。 似乎会话变量没有被“传输”。

感谢任何形式的帮助。

PS:抱歉英语不好:P

由于

2 个答案:

答案 0 :(得分:1)

据我所知,其他数字必须包含在' '中。试试这个

 $checklogin = "SELECT * FROM users WHERE username ='".$_SESSION['username']."' AND password ='".$_SESSION['password']."'";

我希望这有效。

答案 1 :(得分:0)

要使用$_SESSION变量,请先运行session_start()。您在网站标题中标记为&#34;的示例,&#34;您尚未首先运行session_start()

http://php.net/manual/en/function.session-start.php

  

session_start()根据通过GET或POST请求传递的会话标识符创建会话或恢复当前会话,或通过cookie传递。