SESSION变量没有被传递过来

时间:2016-05-22 17:26:41

标签: php session login

我正在尝试检查我的resultId是否存在,以便我可以重定向到我的登录页面,如果它没有。根据我对SESSION变量的理解,这些信息应该传递到我的页面,但它并没有。现在登录后,页面应该重定向到主页,但它会直接回到登录界面,因为它无法在resultId的会话中找到值。

我的登录页面:

<?php 
    session_start();
    // Define variables and set to empty values
    $usernameErr = $passwordErr = $loginErr = "";
    $loginName = $loginPass = "";

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $valid = True;

        if (empty($_POST['loginName'])) {
            $usernameErr = "Please enter your username";
            $valid = False;
        } else {
            $loginName = test_input($_POST['loginName']);
            $_SESSION['loginName'] = $loginName;
        }

        if (empty($_POST['loginPass'])) {
            $passwordErr = "Please enter your password";
            $valid = False;
        } else {
            $loginPass = test_input($_POST['loginPass']);
            $_SESSION['loginPass'] = $loginPass;
        }

        // If valid connect to database
        if ($valid) {
            $username = "root";
            $password = "";
            $servername = "";

            try {
                $pdo = new PDO("mysql:host=$servername; dbname=capstonedb", $username, $password);
                // Set the PDO error mode to exception
                $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            } catch (PDOException $e) {echo "Connection failed: " . $e->getMessage();}

            // Select username and password from database 
            // and compare with user input.
            $sql_login = "SELECT id FROM login
                        WHERE username = '$_SESSION[loginName]'
                        AND password = '$_SESSION[loginPass]'";
            $result = $pdo->query($sql_login);
            $resultId = $result->fetch();
            $_SESSION['resultId'] = $result->fetch();           

            if ($resultId['id'] != null) {
                // Login successful 
                // Redirect to home.php
                header('location: home.php');
            } else {
                $loginErr = "Incorrect login/password";
            }   

            // Close the connection
            session_destroy();
            $pdo = null;
        }
    }

    // Function to sanitize data
    function test_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }


?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
        <meta name="description" content="">
        <meta name="author" content="">
        <link rel="icon" href="../../favicon.ico">
        <title>Childcare Facilities</title>
        <!-- Bootstrap core CSS -->
        <link href="css/bootstrap.min.css" rel="stylesheet">
        <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
        <!--[if lt IE 9]>
          <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
          <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
        <![endif]-->
        <link href="mystyles.css" rel="stylesheet">
        <style>
            .error {
                color: red;
            }
        </style>
    </head>


    <body>
        <div class="jumbotron" style="margin-bottom:100px">
            <div class="container">
                <img src="Mountain.jpg" width="138px" height="138px" alt="logo" style="float:right" class="main-logo">
            <h1 style="color: white" style="float:clear">Smileside Childcare Facilities</h1>
            </div>
        </div>

        <div class="col-md-4"></div>
        <div class="col-md-4">
            <div class="panel panel-default" style="margin-bottom:50px;">
                <div class="panel-heading" style="background-color: #9ad3de; text-align:center;">
                    <h3><strong>Login</strong></h3>
                    <span class="error"><strong><?php echo $loginErr ?></strong></span>
                </div>
                <div class="panel-body">
                    <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
                        <div class="form-group">
                            <label for="loginName" class="col-sm-3 control-label">Username: </label>
                            <div class="col-sm-8">
                                <input class="form-control" type="text" name="loginName" />
                                <span class="error">* <?php echo $usernameErr; ?></span>
                            </div>
                        </div><br /><br />
                        <div class="form-group">
                            <label for="loginPass" class="col-sm-3 control-label">Password: </label>
                            <div class="col-sm-8">
                                <input class="form-control" type="password" name="loginPass" />
                                <span class="error">* <?php echo $passwordErr; ?></span>
                            </div>
                        </div>
                        <br />
                        <br />
                        <input type="submit" class="btn btn-primary pull-right" value="Log In" />
                    </form>
                </div>
            </div>
        </div>

        <div class="navbar navbar-default navbar-fixed-bottom">
            <div class="container">
                <p class="navbar-text pull-left">© 2016 - Built By Michal Patriak
                </p>
            </div>
        </div>


        <!-- Bootstrap core JavaScript
        ================================================== -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script src="js/bootstrap.min.js"></script>
    </body>
 </html>

我的主页php(它是导致此问题的唯一部分):

<?php 
    session_start();
    if(empty($_SESSION['resultId'])) {      
        header("Location: index.php");  // Redirect to login page if not logged in 
    }   
?>

3 个答案:

答案 0 :(得分:0)

检查此代码 而不是

$_SESSION['resultId'] = $result->fetch(); 

应该是

$_SESSION['resultId'] = $resultId['id'];

您必须检查会话是否存在,然后启动会话

if(!isset($_SESSION)){
    session_start();
}
if(!isset($_SESSION['resultId'])){
  header("Location: index.php");  // Redirect to login page
}   

答案 1 :(得分:0)

试试这个

    if (session_status() !== PHP_SESSION_ACTIVE) 
    {
        session_start();
    }   


 if(!isset($_SESSION['resultId'])){
    header("Location: index.php");  // Redirect to login page
 }   

答案 2 :(得分:0)

您必须在变量中保存SESSION,然后将其应用到SQL查询中。它可以减少你的单引号(&#39;)错误。

 $uname=$_SESSION['loginName'];
  $pw=$_SESSION['loginPass'];

    $sql_login = "SELECT `id` FROM `login` WHERE `username` = '$uname' AND `password` = '$pw'";
    $result = $pdo->query($sql_login);
    $resultId = $result->fetch();

试试这个:)