0

I'm building a PHP application, one section of which will export an Excel file when a user submits the last of three pages of HTML forms. This takes a while to process, so on form submit I'm bringing up a "Please Wait" popup with JavaScript prior to processing beginning. The file is then created and downloaded on the users machine by setting the headers below

header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' .  $fileName . '.xls' .'"');
header('Cache-Control: max-age=0');

The problem I'm having, is that I then need to redirect the user back to the first page of the form. I can't echo a javascript location.href call, as the content-type has already been changed before this, so it never makes it to screen. Neither can I use a standard PHP header('Location: x') redirect for the same reason.

My question is, after diverting output to a file in the way above, how can I then either get the output back to screen to echo a JavaScript redirect, or redirect the user to a new page in some other way?

As always, any help is much appreciated.

James

James Dinsdale
  • 789
  • 8
  • 23
  • You can't do that. One Request = one Response. If the request was "give me that file", you cannot send that file AND some additional stuff. This is not a PHP problem, but the way HTTP works. – Honk der Hase Jun 05 '13 at 09:49
  • Refer the link http://stackoverflow.com/questions/822707/php-generate-file-for-download-then-redirect – Kiren S Jun 05 '13 at 09:49

3 Answers3

0

Try this code

 <?php
    echo "<script>
    window.location='page.php';
    </script>";
    ?>
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
0

As described above there's no way to send new headers after the page has loaded, but there is a way to get the functionality I wanted.

The answer was to create an AJAX call, running in a setInterval loop which looks for a $_SESSION variable in the PHP. This session variable is set after the Excel file is created (where I was previously trying to place the redirect), causing the AJAX function to return success, and then perform a location.href redirect to the correct page.

James Dinsdale
  • 789
  • 8
  • 23
0

the below code can do it. it can redirect you last page from where the download request is sent no need to echo content only readfile can do it so the page will automatically unload after download box appear.

$path is the path of your file to make user download

    header("Content-type: application/vnd.ms-excel");
    header('Content-Disposition: attachment; filename="'.$path.'"');  
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header("Cache-Control: public");
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($path));
    readfile($path);
Sagar Rabadiya
  • 4,126
  • 1
  • 21
  • 27