In what scenarios would it be more beneficial to use sessions over cookies for user authentication in PHP?

Sessions are more secure for user authentication in PHP because the data is stored on the server-side rather than on the client-side like cookies. This prevents users from tampering with their authentication data. Sessions also automatically expire when the user closes their browser, providing an added layer of security.

// Start a session
session_start();

// Set session variables
$_SESSION['user_id'] = $user_id;

// Check if user is authenticated
if(isset($_SESSION['user_id'])){
    // User is authenticated
    echo "User is authenticated";
} else {
    // User is not authenticated
    echo "User is not authenticated";
}