Search code examples
phphttp-headers

PHP: download a file after the headers have already been sent


I have a number of PHP scripts which work together to generate a table of data and I would like to allow my users to download this data. Here's the accepted solution for this feature.

$fp = fopen('php://output', 'w');
if ($fp && $result) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="export.csv"');
    header('Pragma: no-cache');
    header('Expires: 0');
    fputcsv($fp, $headers);
    while ($row = $result->fetch_array(MYSQLI_NUM)) {
        fputcsv($fp, array_values($row));
    }
    die;
}

The problem is that my page's headers have already been sent and retooling the various scripts to buffer all the content would be too complex. Is there a way this can be accomplished with the headers having already been sent?


Solution

  • simply enough, no

    what you could do is redirect the request to a new request which is a standalone download script

    As headers have already been sent, all you can really do is give your users a link to follow, perhaps with some Javascript to automatically follow the link, or perhaps an old school "meta refresh" in your HTML head

    eg

    https://www.w3docs.com/snippets/html/how-to-redirect-a-web-page-in-html.html

    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="refresh" content="7; url='https://www.w3docs.com'" />
      </head>
      <body>
        <p>You will be redirected to w3docs.com soon!</p>
      </body>
    </html>