How can sessions be effectively used to manage user logins and access control in PHP applications?
Sessions can be effectively used to manage user logins and access control in PHP applications by storing user authentication information in session variables. When a user logs in successfully, their user ID or other relevant data can be stored in a session variable. This information can then be checked on each page to determine if the user is logged in and has the necessary permissions to access certain content.
<?php
// Start the session
session_start();
// Check if the user is logged in
if(isset($_SESSION['user_id'])) {
// User is logged in, perform access control checks here
echo "Welcome, User " . $_SESSION['user_id'];
} else {
// Redirect to login page if user is not logged in
header("Location: login.php");
exit();
}
?>