What potential pitfalls should be avoided when naming and handling image files for download in PHP?

One potential pitfall to avoid when naming and handling image files for download in PHP is using user input directly as the filename. This can lead to security vulnerabilities such as directory traversal attacks. To mitigate this risk, sanitize the filename before saving or serving it to the user.

// Sanitize the filename before saving or serving it
$filename = preg_replace("/[^a-zA-Z0-9\.]/", "", $_GET['filename']);