Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add http header to wordpress

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);
}
like image 354
obs Avatar asked Jul 20 '26 17:07

obs


2 Answers

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

like image 118
Peter Cullen Avatar answered Jul 23 '26 05:07

Peter Cullen


You need to use a hook that executes before Wordpress adds anything to the output. One such hook is "init"

function do_my_stuff_with_headers() {
    // ...
}
add_action( 'init', 'do_my_stuff_with_headers' );
like image 26
C. E. Avatar answered Jul 23 '26 06:07

C. E.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!