What are the best practices for handling user authentication in PHP?

User authentication is a critical aspect of web applications to ensure that only authorized users can access certain resources. To handle user authentication securely in PHP, it is recommended to use password hashing with functions like password_hash() and password_verify(), store user credentials in a secure database, use prepared statements to prevent SQL injection attacks, and implement proper session management to keep track of authenticated users.

// Sample code for user authentication in PHP

// Check if the user submitted the login form
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve user input
    $username = $_POST["username"];
    $password = $_POST["password"];

    // Query the database to retrieve user credentials
    $query = "SELECT * FROM users WHERE username = ?";
    $stmt = $pdo->prepare($query);
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    // Verify the password using password_verify()
    if ($user && password_verify($password, $user["password"])) {
        // Start a new session and set user authentication
        session_start();
        $_SESSION["user_id"] = $user["id"];
        // Redirect to the dashboard or protected page
        header("Location: dashboard.php");
        exit();
    } else {
        // Display an error message for invalid credentials
        $error = "Invalid username or password";
    }
}