How can header redirection be used effectively in PHP to manage browser navigation and session data?

To manage browser navigation and session data effectively in PHP, header redirection can be used to redirect users to different pages based on certain conditions or actions. This can help control the flow of the application and maintain session data across different pages.

<?php
session_start();

// Check if user is logged in
if(!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// Redirect user to dashboard if already logged in
if(isset($_SESSION['user_id'])) {
    header("Location: dashboard.php");
    exit();
}
?>