How can PHP developers securely handle user input like GET parameters in a file download function?
When handling user input like GET parameters in a file download function, PHP developers should always sanitize and validate the input to prevent security vulnerabilities such as directory traversal attacks. One way to securely handle user input is to use PHP's `basename()` function to extract the filename and ensure it is safe to use in file operations.
// Get the filename from the GET parameter
$filename = basename($_GET['file']);
// Validate the filename to prevent directory traversal attacks
if (preg_match('/^[a-zA-Z0-9]+\.[a-zA-Z]{3,4}$/', $filename)) {
// Proceed with file download
$file_path = '/path/to/files/' . $filename;
if (file_exists($file_path)) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '"');
readfile($file_path);
exit;
} else {
echo 'File not found.';
}
} else {
echo 'Invalid filename.';
}
Keywords
Related Questions
- What are some alternative methods to str_replace for replacing variables in PHP text?
- How can the PHP code be modified to ensure that the conversion process is triggered correctly when the user clicks on the conversion buttons on the webpage?
- How can RTF be used as an alternative file type for generating Word documents in PHP?