How can the use of session IDs for user authentication in PHP be optimized for security and efficiency?

To optimize the use of session IDs for user authentication in PHP for security and efficiency, it is recommended to regenerate the session ID periodically to prevent session fixation attacks and ensure that each session has a unique identifier. This can be achieved by setting a timeout for the session and regenerating the session ID after a certain period of inactivity.

// Set session timeout to 30 minutes
ini_set('session.gc_maxlifetime', 1800);

// Regenerate session ID every 30 minutes
if (isset($_SESSION['last_activity']) && time() - $_SESSION['last_activity'] > 1800) {
    session_regenerate_id(true);
    $_SESSION['last_activity'] = time();
} else {
    $_SESSION['last_activity'] = time();
}