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.";
}
?>