How can PHP sessions be used as an alternative to query strings for access control?
Using PHP sessions for access control can provide a more secure and convenient alternative to passing sensitive information through query strings. By storing user authentication data in session variables, you can easily check and validate user permissions throughout the session without exposing them in the URL. This approach helps prevent unauthorized access and keeps sensitive information hidden from users.
<?php
session_start();
// Check if user is logged in
if(!isset($_SESSION['user_id'])) {
// Redirect to login page if not logged in
header("Location: login.php");
exit();
}
// Check user permissions
if($_SESSION['role'] !== 'admin') {
// Redirect to unauthorized page if user is not an admin
header("Location: unauthorized.php");
exit();
}
// Continue with protected content
echo "Welcome, Admin!";
?>