PHP: post a link to download file
I found this code that allows me to opens a window and allows the user to download a file (download.php)
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
It works well to allow the user to download a file from the server via a pop up window, but I have two issues:
Before executing this block of code, I have some text printing on the screen (browser). However, w开发者_开发知识库hen the .php file is executed with this block at the very end, nothing prints on the screen, and it goes directly to the download. How do I ensure that things are printed on the browser and then allow the file to be downloaded?
Then, I thought maybe I'll instead insert a link after things are printed, but I'm having trouble getting this to work. When I click on the link to download (href='download.php'), a blank screen is returned and nothing else.
Could someone chime in and help? TIA!
You can't return HTML for the browser and a file download from a single page request from the browser. It expects one or the other. You could open a popup window with text, which then does a Javascript redirect to a second PHP script which sends the file.
Anything you echo will be part of your download. You need two separate pages... one to display your text, and another just for the file.
Each page can be parsed in one way only, html/pdf/image/download file etc...
Solution: Do what you want the users see in HTML (link/text what ever) and when they press the download link you open it inside a hidden iframe.
Now, do not come and complain this is not a kick ass way to solve this, we are in 2011, etc
This is the only way (except using Java or Flash) to solve this (Might be html5 will have a nifty solution, but most users browsers do not support this).
精彩评论