2

Possible Duplicate:
Forcing to download a file using PHP

So i am selling something, and I want the file download to start when users go to the thanks page.

The location of the file is stored in $install, now when user visitsthanks.php, how do i start the file download automatically?

Thanks.

Community
  • 1
  • 1
steve
  • 31
  • 2
  • 8

3 Answers3

2

The majority of what you want to do is actually going to be done in Javascript.

You PHP code will serve up the thanks page, and after it is loaded, you will want to direct a hidden iFrame in your page to a page which serves up the file as a download, using the following headers:

header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=yourfile.txt");
readfile($pathToFile);
Tyler Carter
  • 60,743
  • 20
  • 130
  • 150
  • Javascript? Why? What's wrong with `location` and `redirect` headers? And why would he need to use "hidden iframe"? – binaryLV Apr 15 '11 at 06:25
  • @binaryLV Because I imagine he wants people to *see* and *read* thanks.php. If you used a redirect, they would never see the page. – Tyler Carter Apr 15 '11 at 06:27
  • 1
    Why not? Open "thanks.php" page and send "refresh" header (not "redirect", as I wrote before). What's the problem? – binaryLV Apr 15 '11 at 07:02
1
<?php
// place this code inside a php file and call it f.e. "download.php"
$path = $_SERVER['DOCUMENT_ROOT']."/path2file/"; // change the path to fit your websites document structure
$fullPath = $path.$_GET['download_file'];
if ($fd = fopen ($fullPath, "r")) {
    $fsize = filesize($fullPath);
    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);
    switch ($ext) {
        case "pdf":
        header("Content-type: application/pdf"); // add here more headers for diff. extensions
        header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
        break;
        default;
            header("Content-type: application/octet-stream");
            header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
    }
    header("Content-length: $fsize");
    header("Cache-control: private"); //use this to open files directly
    while(!feof($fd)) {
        $buffer = fread($fd, 2048);
        echo $buffer;
    }
}
fclose ($fd);
exit;
// example: place this kind of link into the document where the file download is offered:
// <a href="download.php?download_file=some_file.pdf">Download here</a>
?>
Elzo Valugi
  • 27,240
  • 15
  • 95
  • 114
Ram
  • 11
  • 2
1

The alternative to a javascript redirect is using a meta refresh tag in your HTML. It works even when javascript is disabled.

cweiske
  • 30,033
  • 14
  • 133
  • 194