What are the best practices for detecting and preventing unauthorized access to directories/files in PHP applications?

Unauthorized access to directories/files in PHP applications can be prevented by implementing proper access control measures. This includes setting appropriate file permissions, validating user input, and using secure authentication methods. Additionally, it is important to avoid exposing sensitive information in error messages or logs to prevent potential attackers from gaining unauthorized access.

// Example of preventing unauthorized access to a directory
if (!isset($_SESSION['user_id'])) {
    header("Location: /login.php");
    exit();
}

// Example of preventing unauthorized access to a file
if ($_SESSION['user_role'] !== 'admin') {
    header("HTTP/1.1 403 Forbidden");
    exit("You do not have permission to access this file.");
}