I know this question has been asked many times before but I can’t find an answer to suit my needs.
I need to find a way to force the download of a file and then, after the download has started, redirect to a “thanks for downloading” page.
So far I have:
<?php
ob_start();
$token = $_POST['validationCode'];
if(isset($token)){
$connect = mysql_connect('localhost', 'root', 'root');
$db = mysql_select_db('mydb');
if (!$connect || !$db){
die('Connect Error (' . mysql_connect_errno() . ') '
. mysql_connect_error());
}
$sql = mysql_query("SELECT * FROM emailaddresses WHERE token='$token'");
$result = mysql_fetch_array($sql);
if($result){
header('Location: complete.php');
header('Content-type: application/mp3');
header('Content-Disposition: attachment; filename=track.mp3');
$f = file_get_contents('downloads/track.mp3');
print $f;
$sql = "UPDATE emailaddresses SET download=1 WHERE token='$token'";
$result = mysql_query($sql);
}
else{
echo "There was a problem downloading the file" . mysql_error();
}
}
ob_end_flush();
?>
It’s important to hide the download file’s location otherwise I would have just created an HTML link to the file.
I obviously can’t put a redirect header below the other headers as it just won’t work. I can’t really see where to go from here apart from opening this in a pop-up and directing the main window to the “thank you” page – but that is a LAST resort.
Can anyone give any suggestions?
Cheers,
Rich
There really isn’t much choice. If your primary goal is to hide the URL, that’s a lost cause anyway. For good usability, you usually include the plain link on the page anyway (“Download doesn’t start? Click here…”), since the user may accidentally cancel the redirect at just the wrong time to irrevocably kill the download.
You cannot output anything other than the file itself in the same request/response. You could try multi-part HTTP responses as suggested by @netcoder, but I’m not really sure how well that’s supported. Just start with the assumption that there’s one “wasted” request/response in which only the file is downloaded and nothing else happens. The way things usually work with this restriction is like this:
<meta>refresh or HTTPRefreshheader that causes a delayed redirect to the URL of the file.Look at http://download.com for an example of this in action.
You can make the download location for the file be a script that only returns the file if the user is allowed to download the file. You can pass some temporary token between the “Thank you” page and the file download page to verify that the download is allowed.