How can the efficiency and security of the PHP script be enhanced to prevent unauthorized users from accessing the site?

To enhance the efficiency and security of a PHP script to prevent unauthorized users from accessing the site, you can implement user authentication using sessions. This involves checking if a user is logged in before allowing access to certain pages or functionality. Additionally, you can use secure coding practices such as input validation and parameterized queries to prevent SQL injection attacks.

<?php
session_start();

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

// Secure database query example
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $_SESSION['user_id']);
$stmt->execute();
$user = $stmt->fetch();