Are there any best practices to follow when creating and downloading zip files in PHP?

When creating and downloading zip files in PHP, it is important to follow best practices to ensure the process is secure and efficient. One common practice is to sanitize user input to prevent any malicious code injections. Additionally, it is recommended to set appropriate headers for the file download, handle errors gracefully, and properly clean up temporary files after the download is complete.

<?php

// Sanitize user input for file name
$zipFileName = filter_var($_GET['filename'], FILTER_SANITIZE_STRING);

// Create a new zip file
$zip = new ZipArchive();
$zip->open($zipFileName, ZipArchive::CREATE);

// Add files to the zip archive

// Close the zip file
$zip->close();

// Set appropriate headers for file download
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . $zipFileName . '"');
header('Content-Length: ' . filesize($zipFileName));

// Output the zip file for download
readfile($zipFileName);

// Clean up temporary files
unlink($zipFileName);
?>