How can PHP code be optimized to ensure proper cookie handling for user login?

To optimize PHP code for proper cookie handling in user login, it is important to set secure and httponly flags on cookies to prevent them from being accessed by malicious scripts. Additionally, setting a proper expiration time for the cookie can enhance security. Finally, always validate and sanitize user input to prevent any potential security vulnerabilities.

// Set cookie with secure and httponly flags
setcookie("user_id", $user_id, time() + 3600, "/", "", true, true);