When should sessions be preferred over global variables in PHP?

Sessions should be preferred over global variables in PHP when you need to store user-specific data across multiple pages or requests. Sessions provide a way to store data on the server side and associate it with a specific user, ensuring better security and scalability compared to global variables.

// Start the session
session_start();

// Set a session variable
$_SESSION['user_id'] = 123;

// Retrieve the session variable
$user_id = $_SESSION['user_id'];