How can sessions be effectively managed in PHP?
Sessions in PHP can be effectively managed by setting session variables, checking for session existence, and destroying sessions when they are no longer needed. This can help ensure that user data is securely stored and accessed throughout a user's session on a website.
// Start the session
session_start();
// Set session variables
$_SESSION['username'] = 'example_user';
$_SESSION['email'] = 'user@example.com';
// Check if session exists
if(isset($_SESSION['username'])) {
echo 'Welcome back, ' . $_SESSION['username'];
}
// Destroy session when no longer needed
session_unset();
session_destroy();