Are there any best practices for structuring PHP code to prevent unauthorized access to certain files or pages?

To prevent unauthorized access to certain files or pages in PHP, one common best practice is to use session management and user authentication. By checking if a user is logged in and has the necessary permissions before allowing access to restricted files or pages, you can ensure that only authorized users can view the content.

session_start();

// Check if user is logged in
if(!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// Check if user has necessary permissions
if($_SESSION['role'] !== 'admin') {
    header("Location: unauthorized.php");
    exit();
}

// Restricted content goes here
echo "Welcome, admin!";