How can the code be optimized to prevent users from being redirected to the homepage after logging in?

The issue of users being redirected to the homepage after logging in can be solved by checking if the user is already logged in before redirecting. This can be done by adding a condition to check if the user is logged in and redirecting them to a different page if they are already authenticated.

<?php
session_start();

if(isset($_SESSION['user_id'])) {
    header("Location: dashboard.php");
    exit();
}

// Your existing login code here

?>