1

I am writing a plugin and want to force users to download a file immediately when they activate the plugin. Here is the code that I've written so far but doesn't work.

No fatal errors but gives warning "The plugin generated 94 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin."

// Downloader
function dcg_file_downloader() {
    $file = ABSPATH . 'wp-content/uploads/sample.txt';

    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    print $file;
}

// Plugin activation hook
function dcg_activate_plugin() {
    dcg_file_downloader();
    update_option('dcg_plugin_version', '1.0');
}
register_activation_hook( __FILE__, 'dcg_activate_plugin' );

Purpose of achieving this is to backup a specific file (for eg.: .htaccess) before making any changes into it.

Also, Is it a good idea to use ABSPATH to get WordPress installation directory/path?

5
  • Hi. Please elaborate 'Doesn't Work'. I don't know if the code is throwing errors, file not downloading, headers not working, etc.
    – Johansson
    Jul 2, 2017 at 11:58
  • No fatal errors but gives warning "The plugin generated 94 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin."
    – Dipak G.
    Jul 2, 2017 at 12:41
  • This happens if your plugin outputs any data before you are trying to stream the image. Have you tried using header('Location: ');?
    – Johansson
    Jul 2, 2017 at 13:04
  • header('Location: '); doesn't work.
    – Dipak G.
    Jul 2, 2017 at 13:15
  • Check headers_sent() to see where they've been sent, then back trace from there. php.net/manual/en/function.headers-sent.php Jul 4, 2017 at 0:01

1 Answer 1

0

Working with headers is tricky because you have to call them before any output is sent, as described in the Documentation. So if you have any spaces before calling them could be it. Another problem can be if any of your code is causing an error, the error massage count as output so it will trigger headers already sent as described in the answer to this question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.