开发者

How can I create a PHP 'Download will begin shortly' page?

I'd like to create a PHP page which shows a message like

Your download will begin shortly.

If it does not start, please click here to restart the download

i.e., the same type of page that exists on major websites.

It will work like this:

<a href="download.php?file=abc.zip">开发者_如何学Python;Click here</a>

When the user clicks that link, he is led to download.php which shows him that message, and then offers the file for download.

How can I do this?

Thanks so much!


The link needs to do one of two things:

  • point directly to the file on your web server
  • point to a PHP script which will do NOTHING but set the appropriate headers and serve the file as the page body. No text output! See http://teddy.fr/blog/how-serve-big-files-through-php for how to actually serve the file.

One way to get the browser to start the download "on its own" is to use a META REFRESH tag.

Another way is to use JavaScript, such as this (from Mozilla's Firefox download page):

function downloadURL() {
    // Only start the download if we're not in IE.
    if (download_url.length != 0 && navigator.appVersion.indexOf('MSIE') == -1) {
        // 5. automatically start the download of the file at the constructed download.mozilla.org URL
        window.location = download_url;
    }
}

// If we're in Safari, call via setTimeout() otherwise use onload.
if ( navigator.appVersion.indexOf('Safari') != -1 ) {
    window.setTimeout(downloadURL, 2500);
} else {
    window.onload = downloadURL;
}


<?php
// download.php
$url = 'http://yourdomain/actual/download?link=file.zip'; // build file URL, from your $_POST['file'] most likely
?>
<html>
    <head>
        <!-- 5 seconds -->
          <meta http-equiv="Refresh" content="5; url=<?php echo $url;?>" />
    </head>
    <body>
        Download will start shortly.. or <a href="<?php echo $url;?>">click here</a>
    </body>
</html>


If you want to be sure the file will be downloaded (as opposed to shown in the browser or a browser plugin), you can set the Content-Disposition HTTP header. For example, to force PDFs to download instead of opening in the browser plugin:

header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="foo.pdf"');
readfile('foo.pdf');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜