php - 会话没有进行但变量是

时间:2021-10-22 06:55:15

I have a page (index.php) which has a login form. When a user logs in, it checks the credentials and if correct, creates a session, sets two variables, auth to yes and user to the username, and redirects to another page(pihome.php) via echoing a javascript window.location.href command. This is where the problem starts. On this page if I run session_start() it used to say session has already been created, ignoring but I was able to access the variables from the previous page. Now using an if condition with session_status() it session_start() works. I have a Logout button on this page which goes to another page (Logout.php). On that page when I try to run session_destroy() it says a session has not been started and when I try to echo the variables it says they have not been defined.

我有一个页面(index.php),它有一个登录表单。当用户登录时,它会检查凭据,如果正确,则创建会话,设置两个变量,auth为yes,user为用户名,并通过回显javascript window.location.href重定向到另一个页面(pihome.php)命令。这是问题开始的地方。在这个页面上,如果我运行session_start(),它曾经说过已经创建了session,忽略但我能够访问上一页的变量。现在使用带有session_status()的if条件,session_start()可以正常工作。我在这个页面上有一个Logout按钮,它转到另一个页面(Logout.php)。在该页面上,当我尝试运行session_destroy()时,它表示会话尚未启动,当我尝试回显变量时,它表示尚未定义。

While browsing SO for solutions I saw certain solutions that applied to variables not being carried over but I can access them on the pihome.php page but logout.php doesn't let me access them or execute session_destroy(). I would like to know if I'm using the sessions correctly and if I should place session_start() at the beginning of every page and how to correctly access the variables. Thanks!

在浏览SO以寻找解决方案时,我看到某些解决方案适用于未被转移的变量,但我可以在pihome.php页面*问它们,但是logout.php不允许我访问它们或执行session_destroy()。我想知道我是否正确使用会话,是否应该在每个页面的开头放置session_start()以及如何正确访问变量。谢谢!

index.php

<!DOCTYPE html>
<html>
<head>
<title>PiHome Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"     href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script     src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">    </script>
<script     src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js">    </script>
<link rel="stylesheet" href="standardstyle.css">
</head>
<body id="override-background">
<?php
session_start();
?>
<?php
if(isset($_SESSION["Auth"])){
if($_SESSION["Auth"] == "yes"){
    echo '<script type="text/javascript">
        window.location.href = "pihome.php";
        </script>';
}
else{

}}
else{

}
?>

<div class="jumbotron">
<h1 class="text-center">PiHome<br/><small>v1.0.0</small></h1>
</div>

<div class="container-fluid">
<div class="well col-3">
<img src="piHome.png" alt="piHome_logo" class="img-rounded"     style="display:block;"></img>
<h3 class="text-center">Login</h3>
<form role="form" action="index.php" method="post">
  <div class="form-group">
    <label for="user">Username</label>
    <input type="text" class="form-control" id="email" name="user">
  </div>
  <div class="form-group">
    <label for="pwd">Password:</label>
    <input type="password" class="form-control" id="pwd" name="pass">
  </div>
  <div class="checkbox">
    <label><input type="checkbox" name="remember"> Remember me</label>
  </div>
<input type="submit" class="btn btn-primary btn-block" value="Login">
<form>
</div>
</div>


<?php
$server = "localhost";
$user = "root";
$pass = "";
$db = "pihome_users";

//Database Connection
$conn = mysqli_connect($server, $user, $pass, $db);

//Check Connection
if($conn->error){
    die("Connection Failed: "+ $conn.error);
}
if(isset($_POST['user'])){
    //echo "Set<br>";
//User Authentication
$inputuser = $conn->escape_string($_POST['user']);
$inputpass = $conn->escape_string($_POST['pass']);
//echo $inputuser."<br>";
//echo $inputpass."<br>";

$sql = 'SELECT * FROM users WHERE username="'.$inputuser.'"';
//echo $sql;

//Execute
$result = $conn->query($sql);
if($conn->error){
    echo "Load Error";
}
if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    if($inputpass == $row["password"]){
        echo '<div class="alert alert-success fade in">
        <a href="#" class="close" data-dismiss="alert" aria-    label="close">x</a>
        Your credentials are correct
        </div>';
        echo '<script type="text/javascript">
        window.location.href = "pihome.php";
        </script>';
        $_SESSION["Auth"] = "yes";
        $_SESSION["User"] = $inputuser;
    }else{
        echo '<div class="container-fluid"><div class="alert alert-danger     fade in">
        <a href="#" class="close" data-dismiss="alert" aria-    label="close">x</a>
        Your username or password is incorrect!
        </div></div>';
        $_SESSION["Auth"] =false;
    //echo "Success";
    }

} else {
    //echo "Failed";

}
}
else{
    //echo "Not Set";
}

?>


</body>
</html>

pihome.php

<!DOCTYPE html>
<html>
<head>
<title>PiHome</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet"         href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <script         src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">        </script>
<script         src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js">        </script>
<link rel="stylesheet" href="standardstyle.css">
</head>
<body>
<?php
$sessionstate = session_status();
if($sessionstate == 1){
    session_start();
    echo "Started";
}

?>
<?php
if(isset($_SESSION["Auth"])){
    if($_SESSION["Auth"] != "yes"){
        echo '<script type="text/javascript">
            window.location.href = "index.php";
            </script>';
            echo "You are logged in as: ".$_SESSION["User"];
    }else{
        echo "Auth Passed";
        $_SESSION["Auth"] = "yes";
    }
}else{
    echo '<script type="text/javascript">
        window.location.href = "index.php";
        </script>';
    }
?>
<div class="jumbotron">
<h1 class="text-center">PiHome<br/><small>v1.0.0</small></h1>
</div>

<div class="container-fluid">
<div class="well col-3">
<h3 class="text-center">Status</h3>
<div id="status">
</div>
</div>

<script>
function AJAX_JSON_Req( url )
{
    var AJAX_req = new XMLHttpRequest();
    AJAX_req.open( "GET", url, true );
    AJAX_req.setRequestHeader("Content-type", "application/json");

    AJAX_req.onreadystatechange = function()
    {
        if( AJAX_req.readyState == 4 && AJAX_req.status == 200 )
        {
            var response = JSON.parse( AJAX_req.responseText );
            //document.write( response.controls[0].type );
            document.getElementById("status").innerHTML =     response.controls[0].type + " " + response.controls[0].state;
        }
    }
    AJAX_req.send();
}

AJAX_JSON_Req( 'status.json' );
</script>
<a href="logout.php">Logout</a>
</div>

</body>
<html>

logout.php

<?php
$sessionstate = session_status();
if($sessionstate == 1){
    session_start();
    echo "Started";
    session_unset();
}
else if($sessionstate == 2){
    session_destroy();
    echo "destroyed";
}
/*echo '<script type="text/javascript">
        window.location.href = "index.php";
        </script>';*/
?>

1 个解决方案

#1


0  

I solved this by using session_start() before any output including <!DOCTYPE html> as suggested by rjdown in the comments above.

我在上面的评论中通过rjdown建议的任何输出(包括)之前使用session_start()来解决这个问题。

#1


0  

I solved this by using session_start() before any output including <!DOCTYPE html> as suggested by rjdown in the comments above.

我在上面的评论中通过rjdown建议的任何输出(包括)之前使用session_start()来解决这个问题。