How can PHP developers prevent unauthorized access to specific pages in their applications?
To prevent unauthorized access to specific pages in PHP applications, developers can implement user authentication and authorization mechanisms. This involves verifying the user's identity and ensuring they have the necessary permissions to access the requested page. One common approach is to use session management to track authenticated users and restrict access based on their roles or permissions.
session_start();
// Check if the user is logged in
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit();
}
// Check if the user has the necessary role or permission
if ($_SESSION['role'] !== 'admin') {
header("Location: unauthorized.php");
exit();
}
// Authorized user can access the page content below
echo "Welcome, Admin!";