What are best practices for handling user authentication and session management in PHP?

User authentication and session management are crucial aspects of web application security. It is important to securely store user credentials, hash passwords, and validate user input to prevent SQL injection and other attacks. Additionally, using secure session management techniques such as using HTTPS, setting secure flags on cookies, and regularly rotating session IDs can help protect user data.

// Start session
session_start();

// Check if user is logged in
if(!isset($_SESSION['user_id'])) {
    // Redirect user to login page
    header("Location: login.php");
    exit();
}

// Validate user input
$username = htmlspecialchars($_POST['username']);
$password = htmlspecialchars($_POST['password']);

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

// Verify password
if(password_verify($password, $hashed_password)) {
    // User is authenticated
    $_SESSION['user_id'] = $user_id;
    // Redirect user to dashboard
    header("Location: dashboard.php");
} else {
    // Invalid credentials, show error message
    echo "Invalid username or password";
}