What security considerations should be taken into account when displaying files in a directory with PHP?

When displaying files in a directory with PHP, it is important to consider security implications such as preventing unauthorized access to sensitive files, avoiding directory traversal attacks, and ensuring that only allowed file types are displayed. To address these concerns, it is recommended to store the files outside the web root directory, validate user input to prevent directory traversal, and use MIME type validation to restrict the types of files that can be displayed.

<?php
$directory = "/path/to/files/directory/";

if (isset($_GET['file'])) {
    $file = basename($_GET['file']);
    $filepath = $directory . $file;

    // Validate file path to prevent directory traversal
    if (strpos($filepath, $directory) === 0 && file_exists($filepath)) {
        // Check if file type is allowed
        $allowedTypes = ['pdf', 'txt', 'jpg', 'png'];
        $fileExtension = pathinfo($filepath, PATHINFO_EXTENSION);
        
        if (in_array($fileExtension, $allowedTypes)) {
            // Display the file
            header('Content-Type: ' . mime_content_type($filepath));
            readfile($filepath);
            exit;
        }
    }
}

// Handle invalid file or unauthorized access
echo "Invalid file or unauthorized access.";
?>