3

Page 1 links to page 2. Page 2 serves a download using the following code:

header("Content-disposition: attachment; filename= '$filename'");
header('Content-type: application/pdf');
readfile($file);
header("location: mainpage.php");

The result being the user "stays" on page 1 but is served a download.

How can I set things up, so that users remain on page 1 but it refreshes after the download is served.

I don't know javascript so I am hoping for a purely PHP solution.

user187680
  • 663
  • 1
  • 6
  • 20

5 Answers5

2

Didn't know of this before, but it's just one of the nice HTTP headers and most of us already know of it from HTML: Refresh.

Just add the following header call:

header('Refresh: 0; url=http://stackoverflow.com/');
Lars Knickrehm
  • 739
  • 4
  • 14
2

In my opinion I wouldn't think you would necessarily need to refresh page1 at all. You should be able to force the download via a link within page1. See below:

Page1.php with a link

<a href="http://www.domain.com/page2.php?pdf=name-of-pdf">Download PDF</a>

Page2.php

$filename = $_GET['pdf'] . '.pdf';

header('Content-type: application/pdf');
header("Content-disposition: attachment; filename= '$filename'");
header("location: $filename");

This will allow the download to start whilst you remain on page1.

Hope this is what you had in mind.

Ufb007
  • 243
  • 2
  • 8
  • So your explaining exactly what I do. What I want, is actually the opposite. I need this exact effect BUT after the download I need to refresh the page so that it displays "download pdf" as "something else" – user187680 Aug 04 '12 at 00:37
0

You can check what the referer is by $_SERVER['HTTP_REFERER']. So you should be able to put this in you're page1.php:

if($_SERVER['HTTP_REFERER'] == page2.php) {
  echo "<meta http-equiv=\"refresh\" content=\"0;url=http://www.yourdomain.com/page1.php\">";
exit();
}

This way, you check if your visitor is coming from page2.php, and if they are, you only parse a meta-tag which refresh the browser. When it is refreshed, it wouldn't refresh again, because the HTTP_REFERER is now page1.php.

JarroVGIT
  • 4,291
  • 1
  • 17
  • 29
0

No sure if you ever got this answered, but I had the same problem, here is my solution The AJAX jquery

$(function(){

$("#itemList").on("click", "a.downloadLink", function(){ //this binds a click event handler on the itemList container that will listen out for any a with class of downloadLink inside it being clicked

       var link = $(this);
       var item = link.parent();
       var forId = item.data("itemid");
       var started = new Date(); //the alternative to tracking time elapsed is to just use a simple counter you increment - "poll 5 times" etc. if your doing .5 second intervals, then 5 times = 2.5 seconds for example. Time elapsed may result in less polls, if a poll takes a long time to return, for example. Use whichever approach feels better.
       var maxTime = 5000; //5 seconds
       function poll(){
             $.ajax({
                type: "POST",
                url: "Watergetstatus.php", 

                  data: {FID: forId},   //this will be turned into a request for page1?forId=1&oldValue=2  - I expect it in this example to return a json-encoded response of {"changed":true|false, "newHtml":"replacementContent on success"}
                  datatype :'json',
                  success: function(data){
                         if (data.changed=true)
                         {
                         window.location.reload(true);
                         }
                         else {
                               var elapsed = (new Date())-started;
                               //window.location.reload(true);
                               if (elapsed <= maxTime) setTimeout(poll, 500); // Poll again in .5 seconds
                               //else you can assume the link didn't open / work / the database never changed etc - handle or ignore as needed
                          }
                   },
                   error: function() {
                       alert("borken");  //the request to the server bombed out; up to you if you want to simply re-queue for another try like above until the expiry time or if you want to show an error or just simply ignore it.
                   }
             });
       }

       setTimeout(poll, 500); //wait 0.5 seconds before polling
});

});

The HTML had a large list of dynamic links

<div data-itemid="<?php echo $row_Files['FID']; ?> " >
<a class="downloadLink" href="PLC_FILES/WaterCheckOut.php?FID=<?php echo $row_Files['FID']; ?> " target=""><img src="PLCImages/download.fw.png"></a>
</div>

The Poling file watergetstatus.php

mysql_select_db($database_PLC, $PLC);
$query_files = "SELECT * FROM files WHERE FID = '{$_POST['FID']}'";
$files = mysql_query($query_files, $PLC) or die(mysql_error());
$row_files = mysql_fetch_assoc($files);
$totalRows_files = mysql_num_rows($files);

if($row_files['Status'] ==2)
{
        $data= array("changed"=>true); 
        echo json_encode($data);
}
else
{
        $data= array("changed"=>false); 
        echo json_encode($data);
}

THe download file link watercheckout.php

if ( $row_files['Status']==1 ) {

$file_path  = $row_files['FileName'];;
$path_parts = pathinfo($file_path);
$file_name  = $path_parts['basename'];
$file_ext   = $path_parts['extension']; 

 $content_types = array(
            "exe" => "application/octet-stream",
            "zip" => "application/zip",
            "mp3" => "audio/mpeg",
            "mpg" => "video/mpeg",
            "avi" => "video/x-msvideo",
    );
    $ctype = isset($content_types[$file_ext]) ? $content_types[$file_ext] : $ctype_default;



$file = $row_files['FileName'];
$path = "Historical/".date('Y-m-d-His');
$newfile = $path."_".$file;
$today = date('Y-m-d H:i:s');

header('Content-disposition: attachment; filename='.$file);
header("Content-Type: " . $ctype);
header('Content-Length: ' . filesize($file));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
mysql_select_db($database_PLC, $PLC);
mysql_query("UPDATE files SET Status = '2'");

ob_clean();
flush();


readfile($file);
rename($file, $newfile);

I have simplified my code and cut out alot, so it may be missing something, but this was the general frame work that I used and it works for me

Hope this helps someone, as there was not much out there

hounded
  • 666
  • 10
  • 21
-1
//----------------- TOP OF DOWNLOAD_PAGE.PHP ----------------------

$download_code = mysql_real_escape_string(urldecode($_GET['code']));
$download = mysql_real_escape_string(urldecode($_GET['download']));

$self = $_SERVER["PHP_SELF"]."?code=$download_code";

//refresh page after download...

echo"
    <script type=\"text/javascript\">
        function downloadRedirect(){
           var redirect_url = \"$self\";

           setTimeout(\"DoTheRedirect('\"+redirect_url+\"')\",
            parseInt(0.5*1000));
        }
        function DoTheRedirect(url) { window.location=url; }
    </script>
";

...

$filepath = "/var/www/vhosts/YOUR_DOMAIN.com/digital_downloads/";

if (isset($_GET['download'])) {

    $file = $_GET['download'];

    if (file_exists($filepath.$download) && 
is_readable($filepath.$download) && (preg_match('/\.zip$/',$download) || preg_match('/\.zipx$/',$download) )) {

...

    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"".$download."\"");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: ".filesize($filepath.$download));
    ob_end_flush();
    readfile($filepath.$download);


}//end if file_exists


}//end if isset

//----------------- BOTTOM HALF OF DOWNLOAD_PAGE.PHP ----------------------

//link generated to download and call JS to refresh page
echo "<a href=\"".$_SERVER["PHP_SELF"]."?download=$download_id.zipx&code=$download_code\" target=\"_top\" onclick=\"javascript:downloadRedirect()\">Click to Download</a> 
  • A good answer requires more than code. An explanation of how it answers the initial question is required. – JSTL Aug 22 '18 at 17:31