What potential pitfalls should be considered when setting the filename for browser output in PHP?

When setting the filename for browser output in PHP, it is important to consider potential pitfalls such as allowing user input directly as the filename, which could lead to security vulnerabilities like directory traversal attacks. To mitigate this risk, it is recommended to sanitize the filename by removing any special characters and ensuring it only contains alphanumeric characters, dashes, and underscores.

// Sanitize the filename before setting it for browser output
$filename = preg_replace("/[^a-zA-Z0-9-_\.]/", "", $filename);
header('Content-Disposition: attachment; filename="' . $filename . '"');