What are the potential pitfalls of using header() and file_get_contents() to retrieve and display files in an HTML document?

One potential pitfall of using header() and file_get_contents() to retrieve and display files in an HTML document is that it can expose your server to security vulnerabilities, such as remote code execution or directory traversal attacks. To mitigate this risk, it is recommended to sanitize user input and validate file paths before using them in these functions.

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

// Validate and sanitize the file path
if (strpos($file, '..') === false && file_exists($file)) {
    // Set appropriate content type
    header('Content-Type: text/html');

    // Output the file contents
    echo file_get_contents($file);
} else {
    echo 'Invalid file path';
}
?>