What potential pitfalls should be considered when using the header function in PHP to handle image files?

When using the header function in PHP to handle image files, it's important to ensure that the content type is set correctly to avoid potential security vulnerabilities such as content injection attacks. Always validate user input and sanitize file paths before sending them to the header function to prevent directory traversal attacks. Additionally, make sure to set appropriate cache-control headers to prevent caching sensitive image data on the client side.

<?php
// Set the content type to image
header('Content-Type: image/jpeg');

// Validate and sanitize user input for file path
$imagePath = 'images/' . basename($_GET['image']);

// Send the image file to the browser
readfile($imagePath);

// Set cache-control headers to prevent caching
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
?>