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 . '"');
Related Questions
- Is it possible to encrypt PHP code/snippets for added security?
- Are there any best practices for handling SSL certificates in PHP scripts when accessing websites with invalid certificates?
- In what situations would a LEFT JOIN be preferred over other types of SQL joins when working with PHP and MySQL?