2012-10-17 113 views
-1

可能重複:
forcing a file download with php
force download of different files強制從服務器PHP下載

我試圖讓用戶從我的PHP站點下載圖像。我已經看到了一堆關於它的文章,我試圖用從PHP文檔readfile。但我似乎無法讓它工作。

這對於我試圖建立開始下載按鈕的代碼:

 <!-- download image button --> 
    <form class="grid_12" style="text-align: center;" action="../includes/download.php" method="post"> 
     <input type="hidden" name="id" value="<?php echo $photo->id; ?>" /> 
     <input type="hidden" name="img" value="<?php echo $photo->filename; ?>" /> 
     <?php if(isset($_GET['cat'])){?> 
      <input type="hidden" name="cat" value="<?php echo $_GET['cat']; ?>" /> 
     <?php } ?> 
     <div id="download"><input type="submit" name="submit" value="Download Photo" /></div> 
    </form> 

這是我在我的download.php文件中設置(代碼redirect_to的僅僅是一個函數調用頭(地點:VAR),其中VAR是你在傳遞什麼

<?php 
require_once('initialize.php'); 
?> 
<?php 
header("Content-type: application/force-download; filename=".$_POST['img']); 

// Force download of image file specified in URL query string and which 
// is in the same directory as this script: 
if(!empty($_POST['img'])) 
{ 
    $file = $_POST['img']; 
    if (file_exists($file)) { 
     header('Content-Description: File Transfer'); 
     header('Content-Type: application/octet-stream'); 
     header('Content-Disposition: attachment; filename='.basename($file)); 
     header('Content-Transfer-Encoding: binary'); 
     header('Expires: 0'); 
     header('Cache-Control: must-revalidate'); 
     header('Pragma: public'); 
     header('Content-Length: ' . filesize($file)); 
     ob_clean(); 
     flush(); 
     readfile($file); 
     exit; 
    } 

    $addy = "../public/photo.php?id=".$_POST['id']; 
    if(isset($_POST['cat'])){ 
     $addy .= "&cat=".$_POST['cat']; 
    } 
    redirect_to($addy); 
} 
header("HTTP/1.0 404 Not Found"); 
?> 

隱藏的變數,我在郵寄大多爲重定向用戶返回到它們從下載頁面在我的本地主機上,我被重定向到了我的頁面點擊下載按鈕。在我的服務器上,我只是被髮送到註冊爲download.php的空白頁面。我認爲這可能與輸出緩衝有關,因爲我正在獲得空白頁面。這通常意味着在我調用header()函數之前有某種輸出。

如果任何人都可以給我一些見解,以我做錯了什麼在這裏我將不勝感激,感謝您的閱讀。

-Alan

+1

做ob_start();在您的下載文件的頂部 –

+0

您的腳本可能容易受[路徑遍歷](https://www.owasp.org/index.php/Path_Traversal)的影響,該腳本允許讀取服務器上的任何文件。 – Gumbo

+1

你設置'的Content-Type:'頭兩次,我不太知道什麼是RFC講述的是......你可能想先檢查。 – hakre

回答

0

謝謝你的見解,我相信這是什麼hakre和GBD指出的組合。我兩次打電話給標題頭,因爲我已經設置了一個如何設置它的例子。然後我用的例子來自PHP文檔的ReadFile的,以及...

然後我不得不修復的絕對路徑的圖像文件,因爲我只是在文件名發送。再次感謝您的快速幫助,我真的很感激。

**更新

我的本地主機上,但在服務器上對我來說這一切固定的,現在帶我到一個頁面充滿亂碼的符號,而不是在開始下載的......我會考慮這個問題,當我找到解決方案時重新發布。

**修復

首先,我不得不進入我的php.ini文件在服務器上,改變了allow_url_fopen =上,使得服務器可以使用文件的方法,如ReadFile的,FOPEN等。然後我也不得不在文件上添加輸出緩衝,因爲有太多的頭文件調用。在沒有輸出緩衝的情況下,在整個調用建立之前調用第一個緩衝。再次

感謝所有幫助,現在它工作在我的本地主機和服務器上。