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);
Keywords
Related Questions
- What is the significance of the error message "Cannot modify header information - headers already sent" in PHP when setting cookies?
- What are the potential benefits of separating HTML and PHP files in web development?
- What potential issues can arise when using strpos to locate specific characters in a string, especially when the character appears multiple times?