What are some best practices for redirecting users to a specific page after login in PHP?

When a user logs in to a website, it is often necessary to redirect them to a specific page based on their role or previous actions. One common approach is to store the target page in a session variable before the login process and then redirect the user to that page after successful authentication.

// Start the session
session_start();

// Check if the user is logged in
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true) {
    // Check if a redirect page is set
    if(isset($_SESSION['redirect_page'])) {
        // Redirect the user to the specified page
        header('Location: ' . $_SESSION['redirect_page']);
        exit();
    } else {
        // Default redirect if no specific page is set
        header('Location: index.php');
        exit();
    }
} else {
    // Redirect to login page if user is not logged in
    header('Location: login.php');
    exit();
}