Why is it recommended to include session_write_close() and exit; after using header('Location: index.php') in PHP logout functionality?

After using header('Location: index.php') in PHP logout functionality, it is recommended to include session_write_close() and exit; to ensure that all session data is written and the script execution is terminated immediately. This helps prevent any potential issues with session data not being saved properly or further code execution after the redirect.

<?php
session_start();

// Perform logout actions

session_write_close();
header('Location: index.php');
exit;
?>