Are there any security concerns when using PHP to display files from a directory?

When displaying files from a directory using PHP, there is a security concern known as directory traversal. This vulnerability can allow malicious users to access sensitive files outside of the intended directory. To prevent this, it is important to sanitize user input and validate file paths before displaying them.

$directory = "/path/to/directory/";
$filename = isset($_GET['file']) ? basename($_GET['file']) : null;

if ($filename !== null && file_exists($directory . $filename)) {
    // Validate the file path before displaying it
    $filepath = realpath($directory . $filename);

    if (strpos($filepath, $directory) === 0) {
        // File path is within the specified directory, safe to display
        echo file_get_contents($filepath);
    } else {
        // Invalid file path
        echo "Invalid file path";
    }
} else {
    // File not found or not specified
    echo "File not found";
}