How can session management be effectively implemented in PHP for user authentication?

Session management can be effectively implemented in PHP for user authentication by using session variables to store user credentials upon successful login and checking these variables on each page to determine if the user is authenticated. Additionally, setting session timeouts and regenerating session IDs can help enhance security.

// Start the session
session_start();

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

// Set user credentials upon successful login
$_SESSION['logged_in'] = true;
$_SESSION['username'] = 'example_user';

// Logout functionality
if(isset($_GET['logout'])) {
    session_destroy();
    header("Location: login.php");
    exit;
}