• Hi

    I am having problem sending excel files to the browser to download. I have created a client file portal plugin to allow clients to download files securely, but have found a problem when they download files. I have recreated the problem here:

    Without loading WordPress:
    https://www.mccallum-layton.co.uk/downloadtest.php

    Loading WordPress:
    https://www.mccallum-layton.co.uk/downloadtest-with-wp.php

    The code for both:
    Without loading WordPress:

    $file = "Workbook1.xlsx";
    header('Content-disposition: attachment; filename='.$file);
    header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Length: ' . filesize($file));
    header('Content-Transfer-Encoding: binary');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    ob_clean();
    flush();
    readfile($file);

    Loading WordPress:

    $wpload = 'wp-load.php';
    require( $wpload );
    $file = "Workbook1.xlsx";
    header('Content-disposition: attachment; filename='.$file);
    header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Length: ' . filesize($file));
    header('Content-Transfer-Encoding: binary');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    ob_clean();
    flush();
    readfile($file);

    As you can see, the excel file without loading WordPress works file, but when you load WordPress, the file is corrupted.

    Info:
    Server: Microsoft-IIS/8.0
    PHP/5.4.14

    Any advice on what the problem is would be greatly appreciated.

    Thanks

    Jonathan

Viewing 1 replies (of 1 total)
  • Hi Jonathan,
    I know that it could be too late to help you but, on this stackoverflow answer Mike Schinkel explains a nice way to handle file downloads in wordpress.

    You need to add an action for template_redirect and then attach your file on that action handler, for example:

    add_action('template_redirect','yoursite_template_redirect');
    function yoursite_template_redirect() {
      if ($_SERVER['REQUEST_URI']=='/downloads/data.csv') {
        header("Content-type: application/x-msdownload",true,200);
        header("Content-Disposition: attachment; filename=data.csv");
        header("Pragma: no-cache");
        header("Expires: 0");
        echo 'data';
        exit();
      }
    }

Viewing 1 replies (of 1 total)
  • The topic ‘Excel file download corrupted’ is closed to new replies.