In the context of the provided code snippet, how can the PHP script be modified to prevent the insertion of unwanted characters into downloaded files?

To prevent the insertion of unwanted characters into downloaded files, we can sanitize the file name before saving it. This can be done by removing any special characters, spaces, or symbols that could potentially be harmful. One way to achieve this is by using a regular expression to only allow alphanumeric characters, underscores, and hyphens in the file name.

// Sanitize the file name before saving
$filename = preg_replace("/[^a-zA-Z0-9-_\.]/", "", $filename);