What are the best practices for setting sessions in PHP before redirecting with the header() function?

When setting sessions in PHP before redirecting with the header() function, it is important to start the session before setting any session variables. This ensures that the session is properly initialized before any data is stored in it. Additionally, it is recommended to use session_regenerate_id() to prevent session fixation attacks. Finally, make sure to call session_write_close() before redirecting to ensure that all session data is saved.

<?php
// Start the session
session_start();

// Set session variables
$_SESSION['user_id'] = 123;
$_SESSION['username'] = 'john_doe';

// Regenerate session ID to prevent session fixation attacks
session_regenerate_id();

// Save session data
session_write_close();

// Redirect to another page
header('Location: another_page.php');
exit;
?>