What are the benefits of using sessions in PHP for user authentication and data retrieval?
Using sessions in PHP for user authentication and data retrieval provides a secure way to store user information across multiple pages without exposing sensitive data in the URL or form submissions. Sessions allow for persistent data storage on the server side, making it difficult for malicious users to tamper with or access the data. Additionally, sessions can be used to track user activity and personalize the user experience on a website.
// Start a session
session_start();
// Set session variables
$_SESSION['user_id'] = 12345;
$_SESSION['username'] = 'john_doe';
// Retrieve session data
$user_id = $_SESSION['user_id'];
$username = $_SESSION['username'];
// Destroy session
session_destroy();