add http header to wordpress
http-headers, wordpress
Solution
Wordpress has a hook for this. Add the headers to the `send_headers` hook by calling the `add_action` function.
$zip = new ZipArchive();
$zip_name = time().".zip";
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){
$error .= "* Sorry ZIP creation failed at this time<br/>";
}
foreach($post['files'] as $file) {
$zip->addFile($file_folder.$file);
}
$zip->close();
if(file_exists($zip_name)){
add_action( 'send_headers', 'my_headers' );
readfile($zip_name);
// put this somewhere or return it
// so it can be retrieved later, otherwise
// it might print before your headers
// are sent
unlink($zip_name);
}
function my_headers() {
header('Content-type: application/zip');
header('Content-Disposition: attachment;
}
This will all need to go in a function in your `functions.php` file in your theme folder
Problem
i'm trying to build custom zip files on demand and have found some code that seems to work fine http://www.9lessons.info/2012/06/creating-zip-file-with-php.html i've inserted the code in my wordpress template and the only thing is that the `header()` have to be sent before the template is loaded how can i do this with wordpress? heres the code with the headers ``` $zip = new ZipArchive(); // Load zip library $zip_name = time().".zip"; // Zip name if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){ // Opening zip file to load files $error .= "* Sorry ZIP creation failed at this time<br/>"; } foreach($post['files'] as $file){ $zip->addFile($file_folder.$file); // Adding files into zip } $zip->close(); if(file_exists($zip_name)){ // push to download the zip header('Content-type: application/zip'); header('Content-Disposition: attachment; filename="'.$zip_name.'"'); readfile($zip_name); // remove zip file is exists in temp path unlink($zip_name); } ```