会话变量不会阻止未经授权的访问

时间:2020-04-19 23:49:54

标签: php html session-variables

我正在创建登录系统,并且已经完成身份验证,并且用户可以成功登录。但是,我曾尝试在其他页面上检查正确的会话变量,但是即使用户尚未登录,他们仍然可以访问这些页面。

authenticate.php

  <?php
//Start session.
session_start();

//Connect to MySQL
$servername = "localhost";
$username = "root";
$password = "Turtle#98!";
$dbname = "login";

$conn = mysqli_connect($servername, $username, $password, $dbname);

//Check the connection
if (!$conn) {
    die("Connection failed:  " . mysqli_connect_error());
}

// Check if the data from the login form was submitted.
if ( !isset($_POST['username'], $_POST['password']) ) {
    // Could not get the data that should have been sent.
    exit('Please fill both the username and password fields!');
}

// Preparing the SQL statement will prevent SQL injection.
$stmt = mysqli_prepare($conn, ("SELECT password FROM users WHERE username=?"));
if ( !$stmt) {
    die('mysqli error: ' .mysqli_error($conn));
}
//Bind input variables to prepared statement.
mysqli_stmt_bind_param($stmt, 's', $_POST['username']);

//Execute prepared statement.
mysqli_stmt_execute($stmt);

//Store the result to check if account exists.
mysqli_stmt_store_result($stmt);

//Make sure 'users' table is not empty.
if (mysqli_stmt_num_rows($stmt) > 0) {
    //Bind password in table to stmt.
    mysqli_stmt_bind_result($stmt, $password);
    mysqli_stmt_fetch($stmt);
    // Account exists so now to verify the password, as password stored is hashed.
    if (password_verify($_POST['password'], $password)) {
        // User logged in.
        // Create sessions so we know the user is logged in.
        session_regenerate_id();
        $_SESSION['loggedin'] = TRUE;
        $_SESSION['name'] = $_POST['username'];
        //Redirect user to StudentEntry page after successful login.
        header('Location: StudentEntry.php');
        //echo 'Welcome ' . $_SESSION['name'] . '!';
    } else {
        echo 'Incorrect password!';
    }
} else {
    echo 'Incorrect username!';
}

另一页上的会话变量检查

session_start();
// If the user is not logged in redirect to the login page.
if (!isset($_SESSION['loggedin'])) {
    header('Location: UserLogin.html');
    exit;
}

谢谢

0 个答案:

没有答案