I am creating a login system and I have completed the authentication and a user can log in successfully. However, I have tried checking for the correct session variables on other pages but even if a user hasn't logged in they can still access these pages.
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 variable check on other page
session_start();
// If the user is not logged in redirect to the login page.
if (!isset($_SESSION['loggedin'])) {
    header('Location: UserLogin.html');
    exit;
}
Thanks
