How can PHP be used to secure access to a website?

To secure access to a website using PHP, you can implement user authentication and authorization. This involves verifying the identity of users and restricting access to certain pages or features based on their permissions.

// Start a session
session_start();

// Check if the 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 does not have admin role
    header("Location: unauthorized.php");
    exit();
}