Honus Wagner
Honus Wagner

Reputation: 2908

Displaying output before headers are set in PHP

I have an HTML form that submits its data via POST to a server page:

<form id='report-inputs' method='post' action='generate.php'>...</form>

generate.php is does a lot of work with the data its given, to finally dump out an Excel file for download. It does this by cleaning the buffer and setting the headers:

ob_end_clean();
header('Set-Cookie: fileDownloadToken='.$token); 
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="'.$_DATA['title'].'.xlsx"');
$objWriter->save('php://output');

Without ob_end_clean() the file downloads as corrupt. I would like to display some sort of confirmation or something when the page finishes its processing, but the caveat there is that any page output is cleared before render with ob_end_clean().

What can I do to display some content AND deliver the file successfully?

Thanks.

Upvotes: 1

Views: 434

Answers (2)

slashingweapon
slashingweapon

Reputation: 11307

As @mike-b already stated, you can't make the same response do two things at once. But here's what you can do.

  1. Your PHP script should create the download file and save it as a temporary file on the server.
  2. Return a page to the user saying, "Thank you for your interest in Project X..." or whatever.
  3. The output page should, after a decent interval, redirect the user to the download file's URL. Or you could provide an actual link for them to click on. Or both.

Upvotes: 1

beerwin
beerwin

Reputation: 10327

Save the data into a file, display whatever you wish on the screen, and add a Javascript redirect to the file you saved.

Upvotes: 1

Related Questions