How can the use of header() function in PHP impact session variables during login processes?

When using the header() function in PHP during login processes, it's important to ensure that the function is not called after any output has been sent to the browser. This is because header() is used to send raw HTTP headers, including cookies that store session data. If output is sent before calling header(), it can cause errors or prevent the session variables from being properly set. To solve this issue, make sure to call session_start() at the beginning of the PHP script before any output is sent. This initializes the session and allows you to set session variables that will be stored in cookies. Then, use header() to redirect the user after the session variables have been set.

<?php
session_start();

// Check login credentials
if($authenticated){
    $_SESSION['user_id'] = $user_id;
    header("Location: dashboard.php");
    exit();
} else {
    header("Location: login.php?error=1");
    exit();
}
?>