How can PHP sessions be securely used to restrict user access to specific data or functionalities within a system?
To restrict user access to specific data or functionalities within a system using PHP sessions, you can store user roles or permissions in the session data upon login. Then, check these roles or permissions on each restricted page or functionality to determine if the user has the necessary access.
// Start the session
session_start();
// Check if the user is logged in
if(isset($_SESSION['user_id'])) {
// Check user role or permissions
if($_SESSION['role'] == 'admin') {
// Allow access to restricted functionality
} else {
// Redirect to an error page or display a message
header("Location: error.php");
exit();
}
} else {
// Redirect to the login page
header("Location: login.php");
exit();
}
Related questions
-
PHP 7.4 EOL server performance
-
session management form handling cookies
-
checkbox values URLs PHP