How do sessions work in PHP and what are some best practices for using them?

Sessions in PHP allow you to store user data across multiple pages during a user's visit to a website. To start a session, you use the session_start() function at the beginning of each page where you want to access session data. It's important to use session_regenerate_id() to prevent session fixation attacks and to unset or destroy session data when it's no longer needed to free up server resources.

<?php
// Start the session
session_start();

// Set session variables
$_SESSION['username'] = 'JohnDoe';
$_SESSION['email'] = 'johndoe@example.com';

// Regenerate session ID
session_regenerate_id();

// Unset session variables
unset($_SESSION['email']);

// Destroy the session
session_destroy();
?>