How can PHP code be optimized for better performance when handling user authentication?

To optimize PHP code for better performance when handling user authentication, one approach is to use secure hashing algorithms like bcrypt for storing passwords and implementing proper session management techniques to reduce unnecessary database queries. Additionally, utilizing prepared statements to prevent SQL injection attacks and caching authentication data can also improve performance.

// Example of using bcrypt for password hashing
$hashed_password = password_hash($password, PASSWORD_BCRYPT);

// Example of using prepared statements for querying user authentication
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$stmt->execute([$username]);
$user = $stmt->fetch();

// Example of caching authentication data
if (!isset($_SESSION['user'])) {
    $_SESSION['user'] = $user;
}