I have a page.php with a form, user click on the button and is redirected to download.php where I have the following code:
$zip_file = substr_replace($url, 'zip', strrpos($url, '.') + 1);
$zip_path = '/dev/' . $zip_file;
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . $zip_file . '"');
readfile($zip_path);
unlink($zip_file);
header("Location: success.php");
Basically I was very happy because it works very well in local, the download starts and there is the redirect to the success page. When I upload my files on the server, I open page.php, I click on the button and I reach download.php but the download doesn’t start, the redirect works, I’m redirected to success.php without any download. If comment the redirect, header()
, the download starts, so it’s not because of the code (I guess).
My problem is that it’s just on the server that the download does not start before redirect, and I have no idea why. I need to remove the redirect to make it work but I can’t do that.
I hope someone with more experience could help, thank you very much.
2
Answers
The difference between the two installations is that output buffering is enabled on one, but not the other, and also
error_reporting
is either off or hidden on both.The core problem is that you cannot issue a
header()
call after output has started, andreadfile()
will produce output.The server on which the download works will have output buffering disable and not have a working redirect. If error reporting were on it would be producing an error message appended to the end of the file, likely causing an error on extract.
The server on which the download is not working has output buffering enabled and is able to actually process the
header()
call without error, but issuing aLocation:
header is an implicit 30X redirect which cannot have a body, aka contain the file.You cannot have a download that redirects afterwards unless you use Javascript to handle those conditions client-side.
The closest you can get without JS is responding with a regular page that contains a
<meta>
redirect to the download, aka a "your download will start shortly" page.I’ll share a very simple way with javascript to download file and redirect: