How can a Whitelist approach be used to prevent unauthorized access to files on a web server in PHP?

To prevent unauthorized access to files on a web server in PHP, a Whitelist approach can be used. This involves creating a list of allowed files or directories and checking incoming requests against this list before granting access. This helps to restrict access to only the specified files or directories, preventing unauthorized access to sensitive information.

$allowed_files = array('file1.php', 'file2.php', 'directory1/');

$request_file = $_SERVER['REQUEST_URI'];

if (!in_array($request_file, $allowed_files)) {
    header('HTTP/1.1 403 Forbidden');
    exit('Access Forbidden');
}

// Proceed with serving the requested file