How can variable values be properly inserted into PHP headers for file downloads?
When inserting variable values into PHP headers for file downloads, it is important to properly concatenate the variables within the header function to ensure that the values are correctly passed. This can be done by using the concatenation operator (.) to combine the variable values with the header string. Additionally, it is crucial to sanitize and validate the variable values to prevent any security vulnerabilities.
<?php
$file_name = "example.txt";
$file_path = "/path/to/files/";
// Sanitize and validate the file name before using it in the header
if (preg_match('/^[a-zA-Z0-9_\-\.]+$/', $file_name)) {
header("Content-Disposition: attachment; filename=" . $file_name);
header("Content-Type: application/octet-stream");
readfile($file_path . $file_name);
exit;
} else {
echo "Invalid file name.";
}
?>
Related Questions
- How can cURL or file_get_contents() be used to call a PHP page in the background?
- What strategies can PHP developers implement to improve error handling and debugging when encountering issues with MySQL database interactions in their code?
- What are the limitations of using only PHP to display and update data on a webpage without automatic refreshing?