What are the best practices for handling user login forms and session management in PHP?

When handling user login forms and session management in PHP, it is important to properly sanitize and validate user input to prevent SQL injection and other security vulnerabilities. It is also crucial to securely store user passwords using hashing algorithms like bcrypt. Additionally, implementing session management techniques such as using session tokens and setting appropriate session timeouts can enhance security.

<?php
// Validate user input
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$password = $_POST['password'];

// Hash the password
$hashed_password = password_hash($password, PASSWORD_DEFAULT);

// Verify user credentials
// Example: Check if the username and hashed password match a record in the database

// Start session
session_start();

// Set session variables
$_SESSION['username'] = $username;

// Redirect user after successful login
header('Location: dashboard.php');
exit;
?>