What is the best practice for checking session variables in PHP to ensure secure user authentication?

To ensure secure user authentication in PHP, it is important to properly check session variables to prevent unauthorized access. This can be achieved by validating the session data against a known user identifier stored in a secure manner, such as in a database. Additionally, it is recommended to regenerate the session ID after a successful login to prevent session fixation attacks.

session_start();

// Check if user is logged in by verifying session variable
if(isset($_SESSION['user_id'])) {
    $user_id = $_SESSION['user_id'];

    // Query database to get user information based on user_id
    // Perform necessary authentication checks here

    // Regenerate session ID after successful login
    session_regenerate_id();
} else {
    // Redirect user to login page if not logged in
    header("Location: login.php");
    exit();
}