What are some best practices for handling user login redirection in PHP to ensure security and efficiency?

Issue: When handling user login redirection in PHP, it is important to ensure both security and efficiency. One common approach is to use sessions to store user authentication status and redirect them accordingly. Additionally, validating user input and using secure protocols like HTTPS can help prevent security vulnerabilities. PHP Code Snippet:

session_start();

// Check if user is already logged in
if(isset($_SESSION['user_id'])) {
    header("Location: dashboard.php");
    exit();
}

// Validate user input and authenticate user
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Perform user authentication
    // If authentication is successful, set session variables
    $_SESSION['user_id'] = $user_id;
    header("Location: dashboard.php");
    exit();
}

// Display login form
?>
<form method="post" action="login.php">
    <input type="text" name="username" placeholder="Username">
    <input type="password" name="password" placeholder="Password">
    <button type="submit">Login</button>
</form>