简体   繁体   中英

Start download automatically when a user navigates to another page

I was wondering how to accomplish an effect I've seen on several websites, where I click a download now link, it takes me to another page, and the download starts automatically. What is the best way to accomplish this?

Redirect to a page which emits the following headers:

header("Content-Disposition: attachment; filename=$filename");
header("Content-Length: $length");

See this post about the restrictions on $filename .

edit in response to andr's answer, the php equivalent of redirect-after-x-seconds would be:

header("Refresh: 2; url=start_download.php");

(although you should officially specify a complete URL, I think) where start_download.php would contain the two lines above.

First you show the page with some content (please wait, blah blah) and then redirect to the file itself or to the script which outputs the file. The redirect is done either via meta tag or javascript:

  1. html: <meta http-equiv="refresh" content="5;url=http://example.com/foo.zip" /> where «5» is in seconds
  2. js on page load: setTimeout("location.href=http://example.com/foo.zip", 5000) where «5000» is in milliseconds.

If you choose to output the file via php script, follow mvds's answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM