无法访问不同页面中的会话变量

时间:2017-07-19 14:15:36

标签: php html session mysqli

我只是想创建一个简单的登录网站。我将电子邮件ID存储在会话变量中:

$_SESSION['user']=$email;

但是当我尝试在另一个页面中访问此会话变量时,它显示错误:

  

未定义的索引:第11行的C:\ xampp \ htdocs \ web \ home.php中的用户

的login.php

<?php
        if($_SERVER["REQUEST_METHOD"]=="POST")
        {
            $email=$_POST["email"];
            $password=$_POST["password"];

            $bool=true;
            include 'dbs_con.php';
            $query=mysqli_query($conn,"SELECT * FROM user_info WHERE email='$email'");
            if($query === FALSE) { 
        die(mysqli_error($conn)); // TODO: better error handling
    }
            $exists = mysqli_num_rows($query);
            $table_users = "";
            $table_password = "";
            if($exists > 0) //IF there are no returning rows or no existing username
            {
                while($row = mysqli_fetch_assoc($query))
                {
                    $table_users = $row['email']; // the first username row is passed on to $table_users, and so on until the query is finished
                    $table_pass = $row['password'];
                    //echo "current db value".$table_users." & ".$table_pass;

                }
                //  echo "USER INPUT".$email." & ".$password;
                //  echo "current db value".$table_users." & ".$table_pass;
                    if(($email == $table_users) && ($password==$table_pass)) // checks if there are any matching fields
                    {
                        echo "yes";
                        if($password==$table_pass)
                        {
                             $_SESSION['user'] = $email; //set the username in a session. This serves as a global variable
                             echo $_SESSION['user'];
                       header("location: home.php"); // redirects the user to the authenticated home page

                         }

                      else
                       {
                        Print '<script>alert("Incorrect Password!");</script>'; // Prompts the user
                        Print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
                       }
                 }
                else
                {
                    Print '<script>alert("Incorrect username!");</script>'; // Prompts the user
                    Print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
                }
             }
        }
    ?>

home.php

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<header>
    <?php print $_SESSION['user']; ?>
</header>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

你有session_start();在login.php页面上?