I have a Gravity Form where users have checkboxes set up to choose which files to download. For enhanced UX, the form is multi-page and uses AJAX.
Using the following PHP function and Gravity Forms Hook, I am able to loop through the selected checkboxes and add files into a ZIP Archive, but can't currently start the download.
add_filter( 'gform_after_submission_3', 'download_brochures_message', 10, 4 );
function download_brochures_message( $entry ) {
$confirmation = "Your download should begin shortly. \r\n";
$error = "Files not set \r\n";
$file1 = rgar( $entry, '1.1' );
$file2 = rgar( $entry, '1.2' );
$file3 = rgar( $entry, '1.3' );
$file4 = rgar( $entry, '1.4' );
$files = array(
$file1,
$file2,
$file3,
$file4
);
print_r($files);
$zip = new ZipArchive();
$current_time = time();
$file_folder = wp_upload_dir();
$dir = $file_folder['path'];
$zip_file = tempnam( $dir, time() );
$zip->open( $zip_file, ZipArchive::CREATE );
foreach ($files as $file) {
$zip->addFile($file);
}
$zip->close();
echo $zip_file;
header('Content-disposition: attachment; filename="'.$zip_name.'"');
header('Content-type: application/zip');
header('Content-Length: ' . filesize($zip_file));
header("Location: $zip_file");
readfile($zip_file);
}
Since the form submit's via AJAX, the page headers have already been sent and the PHP errors I receive are "Cannot modify header information - headers already sent". How could I modify this code to allow the zip to download?