How can session variables be used to restrict access to user-specific profile pages?
Session variables can be used to restrict access to user-specific profile pages by storing the user's unique identifier (such as their user ID) in a session variable when they log in. Then, on each profile page, you can check if the session variable matches the user ID associated with that page. If they do not match, you can redirect the user to a different page or display an error message.
<?php
session_start();
// Check if user is logged in
if(isset($_SESSION['user_id'])) {
// Check if user has access to this profile page
if($_SESSION['user_id'] != $profile_user_id) {
header("Location: unauthorized.php");
exit();
}
} else {
header("Location: login.php");
exit();
}
?>
Related Questions
- What are some best practices for handling and displaying values retrieved from SQL queries in PHP to ensure accurate output on the browser?
- Are there any best practices recommended for handling complex combination calculations in PHP applications?
- What potential pitfalls should be avoided when handling passwords in a PHP login system?