• I am writing a plugin and have an Archive page which allows the administrator to download and upload files, so that the Custom Post Types can be saved and reconstructed.

    There are several different types of files and options for downloading them. Those options that are invoked by a static link such as the following work fine:

    <a href="admin.php?action=gig_export_all_attributes" title="Export all Attributes as JSON archive file" rel="permalink">Export all Attributes as JSON file</a>

    However, in the case of a couple of options, the user needs to make a selection from a drop-down list and the selection is passed back from an HTML form via a $_POST variable. Only in the case of those two options do I get problems: all of the lines in which header data is written for the purposes of the output file cause the error “PHP Warning: Cannot modify header information – headers already sent by (output started at…”

    The code that creates the files is exactly the same:

    header('Pragma: public');
    		header('Expires: 0');
    		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    		header('Cache-Control: private', false);
    		header('Content-Type: text/plain; charset=utf-8');
    		header('Content-Disposition: attachment; filename="'.$filename.'";');
    		header("Content-Transfer-Encoding: binary");
    
    			// This opens up the output buffer as a "file"
    		$fp = fopen('php://output', 'w');
    
    			// Hack to write as UTF-8 format
    		fwrite($fp, pack("CCC",0xef,0xbb,0xbf));

    Please help!

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter msnewton

    (@msnewton)

    PS. On one platform, the result is that the HTML for the webpage proceeds the data written out for the file. On another platform, the result is that the file contents are written out onto the screen. Clearly the issue is that the code doesn’t realize that two different outputs are intended: HTML for the screen and data for the file.

    Thread Starter msnewton

    (@msnewton)

    FYI, I chanced upon the solution in an online search, tried it, and it works. I hope to prevent others from wasting precious time on such trivial details.

    In a case such as this (creating download files that require _POST variables), the function that creates the file needs to be hooked in with the add_action(‘admin_init’) call.

    Ridiculous, isn’t it?

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘"Cannot modify header" when writing download file invoked from _POST’ is closed to new replies.