How can PHP sessions be effectively used to store and pass user login data securely in a community website with multiple users?

To securely store and pass user login data in a community website with multiple users, PHP sessions can be utilized. When a user logs in, their credentials can be verified and stored in session variables, and these variables can be checked on each page to ensure the user is authenticated. By using session variables, sensitive user data is not exposed in the URL or stored in cookies, enhancing security.

// Start the session
session_start();

// Check if the user is logged in
if(isset($_SESSION['user_id'])) {
    // User is logged in, perform necessary actions
} else {
    // Redirect to login page
    header("Location: login.php");
    exit();
}

// After successful login, store user data in session variables
$_SESSION['user_id'] = $user_id;
$_SESSION['username'] = $username;