What are the best practices for handling session IDs in PHP login scripts?

When handling session IDs in PHP login scripts, it is important to ensure that the session IDs are securely generated, stored, and validated to prevent session hijacking or fixation attacks. One best practice is to regenerate the session ID after a successful login to mitigate the risk of session fixation. Additionally, always use HTTPS to encrypt the communication between the client and server to protect the session data.

// Start or resume a session
session_start();

// Regenerate session ID after successful login
session_regenerate_id(true);

// Validate session ID before granting access
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    // Redirect to login page
    header("Location: login.php");
    exit;
}