What role does session management play in creating a login system in PHP?

Session management plays a crucial role in creating a login system in PHP as it helps to keep track of a user's login status and store relevant information securely. By using PHP session functions, you can create, manage, and destroy sessions to authenticate users and maintain their login state throughout their visit on the website.

<?php
session_start();

// Check if the user is already logged in
if(isset($_SESSION['user_id'])) {
    // User is already logged in, redirect to the home page
    header("Location: home.php");
    exit;
}

// Validate user credentials and set session variables upon successful login
if($_POST['username'] == 'admin' && $_POST['password'] == 'password') {
    $_SESSION['user_id'] = 1;
    // Redirect to the home page after successful login
    header("Location: home.php");
    exit;
} else {
    // Display error message if login credentials are incorrect
    echo "Invalid username or password";
}
?>