I'm struggling with a simple php script that combine files into a single .zip and then start downloading it.
My script is called through AJAX with Wordpress.
The response header seems fine but the response is a large amount of weird characters (see below).
Probably a problem with the zip file encoding but I can't figure it out.
Note that I can find the zip on my server.
The response headers
The php function
function zipFilesAndDownload($file_names,$archive_file_name) {
ob_start();
$zip = new ZipArchive();
$archive_link = WP_CONTENT_DIR . '/uploads/' . $archive_file_name;
// Create the zip file and throw error if problem
if ($zip->open($archive_link , ZIPARCHIVE::CREATE )!==TRUE) {
exit("Cannot create <$archive_file_name>\n");
}
foreach($file_names as $files)
{
// Create the absolute path for the files
$file_full_path = WP_CONTENT_DIR . '/uploads/' . $files;
// Clean the file name to remove date path created by WP (/2014/05/file -> file)
$file = end((explode('/', $files)));
// Check if the file exists
if ( file_exists( $file_full_path ) ){
// Add the file to the zip with the new $file name
$zip->addFile( $file_full_path, $file );
} else {
exit("ERROR file doesn't exist : $file\n");
}
}
$zip->close();
if(file_exists($archive_link)){
// Send the proper header to download the zip
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($archive_link).'"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($archive_link));
ob_end_clean();
flush();
readfile($archive_link);
//unlink($archive_link);
exit;
} else {
exit("ERROR can't find <$archive_file_name>\n");
}
}
The weird characters