How can PHP developers effectively store and retrieve variables in sessions to secure specific areas of a website?

To effectively store and retrieve variables in sessions to secure specific areas of a website, PHP developers can use the $_SESSION superglobal array to store sensitive data that needs to persist across different pages. By setting session variables, developers can authenticate users and restrict access to certain parts of the website based on their session data. This helps in maintaining security and ensuring that only authorized users can access protected areas.

// Start the session
session_start();

// Store a variable in the session
$_SESSION['user_id'] = 123;

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

// Check if the user is authenticated
if(isset($_SESSION['user_id'])) {
    // User is authenticated, grant access to protected area
} else {
    // User is not authenticated, redirect to login page
    header('Location: login.php');
    exit();
}