What are the best practices for integrating a login form on the homepage with access control mechanisms in PHP?

To integrate a login form on the homepage with access control mechanisms in PHP, it is important to securely handle user authentication and authorization. This can be achieved by using PHP sessions to store user credentials securely and implementing proper validation checks before granting access to restricted content.

<?php
session_start();

// Check if the user is already logged in
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true){
    // Redirect the user to the dashboard or restricted content
    header("Location: dashboard.php");
    exit;
}

// Validate user credentials on form submission
if($_SERVER["REQUEST_METHOD"] == "POST"){
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Perform authentication check (e.g. query database)
    if($username === 'admin' && $password === 'password'){
        // Set session variables and redirect to dashboard
        $_SESSION['loggedin'] = true;
        header("Location: dashboard.php");
        exit;
    } else {
        // Display error message for invalid credentials
        $error = "Invalid username or password";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Login Form</title>
</head>
<body>
    <h2>Login Form</h2>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
        <label for="username">Username:</label><br>
        <input type="text" id="username" name="username"><br>
        <label for="password">Password:</label><br>
        <input type="password" id="password" name="password"><br>
        <input type="submit" value="Login">
    </form>
    <?php if(isset($error)){ echo $error; } ?>
</body>
</html>