What is the purpose of using sessions in PHP for user authentication?

Using sessions in PHP for user authentication helps to securely store and manage user login information across multiple pages. This allows the server to verify the user's identity without requiring the user to re-enter their credentials on every page. Sessions also help prevent unauthorized access to restricted areas of a website by checking the user's authentication status before granting access.

// Start the session
session_start();

// Check if the user is logged in
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    // Redirect the user to the login page
    header("Location: login.php");
    exit;
}

// Access the user's information if needed
$user_id = $_SESSION['user_id'];
$username = $_SESSION['username'];