This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Download a file and redirect…or alternative
Basically, we have a PHP file which outputs a file type using PHP headers.
We want it to work like this:
User clicks link, page opens, download prompt comes up and then the page that prompted the download (the main php page) redirects to another page...
How can I go about doing this? I want it to only redirect once the download prompt has been delivered to the user.
So.. sort of a thank you page.
Can this be done like so:
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: public', false);
header('Content-Description: File Transfer');
header('Content-Type: '.$type);
header('Accept-Ranges: bytes');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($file));
/* sleep for say 3 seconds.. */
header('Location: thankyou.php');
exit();
This code was purely written as an example, but how can we create something like this?
So the download prompt pops up, wait say 3 seconds, and then direct the origin page to a thank you page.
HTTP headers are output all at once (save for chunked sending, though I'm a bit hazy on whether HTTP allows that for headers).
This question looks to be similar.
header('Location: thankyou.php');
Will kill your download,
If you sleep you stop every thing and the browser wont receive the file it will just redirect to thank-you.php
Related
On my web application, I want the user to download some information on a page and redirect after the same.
<?php
header('Content-Description: File Transfer');
header('Content-Type: text/force-donwload');
header('Content-disposition: attachment; filename=Your_Fibble_Password.txt');
header('Content-Length: '.strlen($password));
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
header('Pragma: public');
echo $password;
header('location:./');
?>
So Here the location header works and the page is been redirected but the headers for the file transfer above aren't working.
Note: I can't use exit as I got some code executing below it.
As far as I know, it's not possible do this. The technical limitation is: "You can't send headers after the content", so, in this case, you are sending the password to download (in txt format file) and then you try to send more headers to indicate a redirection.
Maybe you could simulate this behaviour from the frontend application, performing a document.location in javascript.
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
Try this code
<?php
echo "<script>
window.location='page.php';
</script>";
?>
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.
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);
I guess I have to break down and ask for help. (Should have done it 3 days ago!)
Here's what happens...
PHP reads session & post variables, builds a .csv file from a mysql query.
it attempts to open a 'Save As' dialog box and when that's done, jump to another page.
I'm using nested functions but when run, the dialog box seems to get run over and never appears.
separately the functions work fine.
when run, the 'save as' dialog box doesn't wait for user input
Can anyone see what I've done wrong or can you redirect my thinking?
$filename points to the created CSV file on the server
$suggname is a default filename users should see in the dialog box.
The code:
holdit($filename,$suggname);
function holdit($filename,$suggname) {
$fp=#fopen($filename, 'rb');
if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) {
header('Content-Type: "application/octet-stream"');
header('Content-Disposition: attachment; filename="'.$suggname.'"' );
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Transfer-Encoding: binary");
header('Pragma: public');
header("Content-Length: ".filesize($filename));
} else {
header('Content-Type: "application/octet-stream"');
header('Content-Disposition: attachment; filename="'.$suggname.'"' );
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Pragma: no-cache');
header("Content-Length: ".filesize($filename));
}
fpassthru($fp);
fclose($fp);
jump();
}
function jump() {
header('Location: return_from_csv.php');
}
You are adding lots of headers to your HTTP response. One of those is Location which instructs the browser to redirect. Obviously it is interpreting that as a higher priority than your other headers.
Decide if you want to redirect or serve a file in your response and do one or the other.
I suspect you have misunderstood the Location header. Read this: http://en.wikipedia.org/wiki/HTTP_location
By the looks of things you are trying to serve the CSV file and then redirect to another page. Sorry, you cannot do this. An HTTP response does one thing and one thing only. You might consider opening your link to the CSV file in another window using the target attribute of <a>.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Forcing to download a file using PHP
When we need to force user to download a file, we use header with several parameters/options. What if I use
header("location:test.xlsx");
This is working :) Is there any drawback of using this shortcut ?
This approach should solve the problems mentioned here
download.php?filename=test.xlsx
if isset ($_GET['filename']){
$filename = $_GET['filename']
}
else{
die();
}
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');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
And of course don't forget to secure this so users can't download other files
There are a few disadvantages to this method:
If the file is one the browser can read, it won't be downloaded (like .txt, .pdf, .html, .jpg, .png, .gif and more), but simply be shown within the browser
Users get the direct link to the file. Quite often, you don't want this because they can give this link to others, so...
it will cost you more bandwidth
it can't be used for private files
if it's an image, they can hotlink to it
All you're doing is redirecting to a file. This is no different than if they went to it directly.
If you are trying to force a download, you need to set your Content-Disposition header appropriately.
header('Content-Disposition: attachment');
Note that you can't use this header when redirecting... this header must be sent with the file contents. See also: https://stackoverflow.com/a/3719029/362536
Not every file is forced to download.
If you were to use that header() on a .jpg the browser won't open the download dialog but will just show the image.
I need to know if a user selected download then clicked the cancel button, which is not the same as readfile having an error. I have inspected the count returned by the readfile function, but it shows the bytes in the file even if the user canceled the download from the Save As dialog.
The reason this is needed is because my site has a one-time download, where a member gives permission for another use to download their file one time, then the permission goes away. But if a member clicks the download button then decides not to download it right then, I dont' want my database to get updated to show they got the file.
This deals with intellectual property protection since the files are the property of the member who uploaded them, and I need to keep an audit trail of exactly what other members downloaded the file in case they start floating around the internet. But if the readfile function always reflects the filesize (meaning those bytes were transferred in some way), I have no way to know if the file was actually downloaded.
I have seen a number of posts about this subject, but no real solutions to what has to be a frequent need - did they download it or not? Just knowing that they clicked the download button doesn't really say whether they decided to go through with it since the Save As dialog box allows someone to cancel the actual completion of the download.
For completeness, here is my download code up until the readfile function:
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename=$download_name");
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("sub/$doc_file"));
ob_clean();
flush();
$wasdownloaded = readfile("sub/$doc_file");
I fear the correct answer is "Impossible" - let me explain: You might be able to correctly figure out, when the file has crossed the wire, but you can't figure out reliably, whether the client threw it away or not.
Example (chronological sequence):
A user on MSIE clicks download and is presented with the "Save where" Dialog.
While this dialog is open, the download is started in the background.
The user navigates around in the dialog or simply does nothing (phone rang, he talks)
The background download is finished, your script sees the download as complete
The user clicks on "cancel"
MSIE deletes the tempfile, the download is never stored in a user-accessible form
Result:
The user sees the file as "not downloaded" - and he is correct
Your app sees the file as "correctly downloaded" - and it is correct
You would first need ignore_user_abort().
This would allow your script to continue on after the user has hit cancel, or escape.
You would then have to print out the file and continuously check with connection_aborted().
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename=$download_name");
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("sub/$doc_file"));
ob_clean();
flush();
$fp=fopen("sub/$doc_file","rb");
while(!feof($fp))
{
print(fread($fp,1024*8));
flush();
ob_flush();
if( connection_aborted() )
{
//do code for handling aborts
}
}
Use this comment on php.net : http://www.php.net/manual/en/function.fread.php#72716
On fclose you would be able to determine if file has been downloaded successful, because your are checking if user aborted connection with connection_status()