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

When handling session IDs and cookies in PHP scripts, it is important to ensure that sensitive information is not exposed and that sessions are secure. To achieve this, it is recommended to use HTTPS, regenerate session IDs after login, set secure and HttpOnly flags for cookies, and validate session data before using it.

// Start a secure session
session_start();

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

// Set secure and HttpOnly flags for cookies
ini_set('session.cookie_secure', 1);
ini_set('session.cookie_httponly', 1);

// Validate session data before using it
if(isset($_SESSION['user_id'])) {
    // Proceed with using the session data
} else {
    // Redirect to login page
    header('Location: login.php');
    exit;
}