How can session-based login systems improve security and user experience in PHP applications?

Session-based login systems can improve security by storing user authentication information on the server side, making it less vulnerable to attacks like session hijacking. This also enhances user experience by allowing users to stay logged in across multiple pages without needing to re-enter their credentials.

// Start the session
session_start();

// Check if user is logged in
if(isset($_SESSION['user_id'])){
    // User is logged in
    echo "Welcome, ".$_SESSION['username']."!";
} else {
    // User is not logged in, redirect to login page
    header("Location: login.php");
    exit();
}