What are some best practices for securely implementing PHP scripts to read and display files from a directory on a website to prevent potential security vulnerabilities?

One best practice for securely implementing PHP scripts to read and display files from a directory on a website is to validate user input to prevent directory traversal attacks. You can achieve this by using functions like realpath() to ensure that the path provided by the user is within the intended directory.

$directory = '/path/to/directory/';
$file = $_GET['file'];

// Validate user input to prevent directory traversal attacks
$realPath = realpath($directory . $file);

if ($realPath !== false && strpos($realPath, $directory) === 0) {
    // Display the file content
    echo file_get_contents($realPath);
} else {
    // Handle invalid input
    echo 'Invalid file path';
}