What are the best practices for handling session IDs in PHP scripts to avoid code corruption?

Session IDs in PHP scripts should be properly sanitized and validated to prevent code corruption. One way to do this is by using session_regenerate_id() function to generate a new session ID after a user logs in or changes their authentication status. This helps prevent session fixation attacks and ensures that each session is unique and secure.

<?php
session_start();

// Check if session ID exists
if (!isset($_SESSION['session_id'])) {
    // Generate new session ID
    session_regenerate_id();
    
    // Store session ID in session variable
    $_SESSION['session_id'] = session_id();
}