How can session variables be affected when using "header('Location...')" for redirection in PHP?

When using "header('Location...')" for redirection in PHP, session variables can be affected because the redirection causes a new request to be made, which can lead to the loss of session data. To prevent this issue, you can use session_write_close() before the redirection to ensure that all session data is saved before the redirection occurs.

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

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

// Save session data
session_write_close();

// Redirect to a new page
header('Location: new_page.php');
exit;
?>