How can the code snippet provided be improved to ensure proper file handling and security measures?

The code snippet provided is vulnerable to directory traversal attacks and does not handle file operations securely. To improve file handling and security measures, we should sanitize the input filename to prevent directory traversal, check if the file exists before attempting to read it, and use file handling functions that provide better security measures.

<?php
$filename = $_GET['filename'];

// Sanitize the input filename to prevent directory traversal
$filename = basename($filename);

// Check if the file exists before attempting to read it
if (file_exists($filename)) {
    // Use file_get_contents to read the file securely
    $file_contents = file_get_contents($filename);
    
    // Output the file contents
    echo $file_contents;
} else {
    echo "File not found";
}
?>