What potential pitfalls should be considered when using PHP to offer files for download on the fly?

One potential pitfall when using PHP to offer files for download on the fly is that the file path may be exposed if not properly handled, potentially leading to security vulnerabilities. To mitigate this risk, it is important to validate user input and sanitize file paths before serving them for download.

// Example code snippet to sanitize file paths before offering them for download
$filePath = $_GET['file']; // Assuming file path is passed as a query parameter
$basePath = '/path/to/files/'; // Define base path for files

// Validate and sanitize file path
$cleanFilePath = realpath($basePath . $filePath);
if (strpos($cleanFilePath, $basePath) !== 0) {
    die('Invalid file path');
}

// Offer file for download
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($cleanFilePath) . '"');
readfile($cleanFilePath);