What is the best practice for setting the filename in the Content-Disposition header for file downloads in PHP?
When setting the filename in the Content-Disposition header for file downloads in PHP, it is best practice to sanitize the filename to prevent any potential security risks, such as directory traversal attacks. One way to do this is by using the `basename()` function to extract the filename from the path and then using `urlencode()` to encode any special characters.
// Get the filename from the path
$filename = basename($file_path);
// Encode the filename to handle special characters
$encoded_filename = urlencode($filename);
// Set the Content-Disposition header with the encoded filename
header("Content-Disposition: attachment; filename=\"" . $encoded_filename . "\"");
Keywords
Related Questions
- How can the Apache server configuration impact the behavior of URL redirection and routing in PHP projects?
- In what scenarios would it be beneficial to let databases handle date and time operations instead of relying solely on PHP functions like mktime?
- In what situations should PHP developers consider using the count() function in PHP to retrieve specific values from arrays?