2011-04-15 176 views
1

可能重複:
Forcing to download a file using PHP如何開始下載文件?

,所以我賣的東西,我想文件下載到啓動,當用戶轉到頁感謝。

該文件的位置存儲在$install,現在當用戶訪問thanks.php時,我該如何自動啓動文件下載?

謝謝。

+0

也許打開新窗口的位置= $ install – 2011-04-15 05:51:33

+0

@experimentX nope..that不會是一個沒有經驗的經驗。 – steve 2011-04-15 05:54:49

+0

的意思..好吧,你打算控制下載嗎? – 2011-04-15 05:56:04

回答

2

你想要做的大部分事情實際上是用Javascript完成的。

您的PHP代碼將提供感謝頁面,加載後,您需要將頁面中隱藏的iFrame指向提供文件下載的頁面,使用以下標題:

header("Content-Type: application/octet-stream"); 
header("Content-Disposition: attachment; filename=yourfile.txt"); 
readfile($pathToFile); 
+0

Javascript?爲什麼? 「位置」和「重定向」標題有什麼問題?爲什麼他需要使用「隱藏的iframe」? – binaryLV 2011-04-15 06:25:25

+0

@binaryLV因爲我想他希望人們*看*和*讀* thanks.php。如果您使用重定向,他們將永遠不會看到該頁面。 – 2011-04-15 06:27:11

+1

爲什麼不呢?打開「thanks.php」頁面併發送「刷新」標題(而不是「重定向」,就像我以前寫的那樣)。有什麼問題? – binaryLV 2011-04-15 07:02:14

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> 
?> 
1

的替代JavaScript重定向在你的HTML使用meta refresh標籤。即使JavaScript被禁用,它也可以工作。

+0

「刷新」也可以用作HTTP標頭。 – binaryLV 2011-04-15 07:03:29