What is the recommended method for handling user authentication in PHP, using sessions instead of cookies?

To handle user authentication in PHP using sessions instead of cookies, you can set session variables upon successful login and check for these variables on restricted pages to ensure the user is authenticated. This method is more secure than using cookies for storing user authentication information.

// Start the session
session_start();

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