可能重複:
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
做ob_start();在您的下載文件的頂部 –
您的腳本可能容易受[路徑遍歷](https://www.owasp.org/index.php/Path_Traversal)的影響,該腳本允許讀取服務器上的任何文件。 – Gumbo
你設置'的Content-Type:'頭兩次,我不太知道什麼是RFC講述的是......你可能想先檢查。 – hakre