In what situations should sessions be preferred over cookies for storing data in PHP applications?
Sessions should be preferred over cookies for storing sensitive data such as user authentication information or session variables that need to be kept secure. This is because sessions store data on the server side, making it less vulnerable to tampering or theft compared to cookies, which are stored on the client side. Additionally, sessions provide a more secure way to store data that should not be accessible to the client.
<?php
session_start();
// Store sensitive data in session variables
$_SESSION['user_id'] = 123;
$_SESSION['username'] = 'john_doe';
// Access the stored data
$user_id = $_SESSION['user_id'];
$username = $_SESSION['username'];
// Destroy the session when no longer needed
session_destroy();
?>