How can PHP sessions be effectively used for user login and data storage?

To effectively use PHP sessions for user login and data storage, you can start a session when a user logs in by setting session variables to store user information. This allows you to keep track of the user's login status and securely store data across multiple pages.

// Start the session
session_start();

// Check if the user is logging in
if($_SERVER["REQUEST_METHOD"] == "POST"){
    // Validate user credentials
    // If valid, set session variables
    $_SESSION["user_id"] = $user_id;
    $_SESSION["username"] = $username;
}

// Check if the user is logged in on other pages
if(isset($_SESSION["user_id"])){
    // Access user data stored in session variables
    $user_id = $_SESSION["user_id"];
    $username = $_SESSION["username"];
}