Search code examples
phpjavascriptheaderdownloadrefresh

refreshing after php serves a download


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.


Solution

  • 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.