How can PHP sessions be effectively used to manage user authentication and authorization?
To manage user authentication and authorization using PHP sessions, you can store user credentials in the session after successful login and check for these credentials on each page to determine if the user is authenticated and authorized to access the content.
// Start the session
session_start();
// Check if user is logged in
if(isset($_SESSION['user_id'])) {
// User is authenticated, perform authorization check here
if($_SESSION['role'] == 'admin') {
// User is authorized as an admin
} else {
// User is not authorized
header("Location: unauthorized.php");
exit();
}
} else {
// User is not authenticated
header("Location: login.php");
exit();
}