簡體   English   中英

Php force Download - 下載損壞的文件

[英]Php force Download - downloading corrupted file

嗨,我正在嘗試允許下載與產品相關的演示文件。 我的代碼是這樣的

if(isset($_POST['submit'])){     
    $root = $_SERVER['DOCUMENT_ROOT'];
    $path = "/download/";
    $path = $root.$path;
$filename = $demo;
$file = $path.$filename;
header('Content-Type: application/force-download');
header("Content-Transfer-Encoding: Binary"); 
header("Content-Disposition: attachment; filename=\"".basename($file)."\";" );
header("Content-Length: ".filesize($file));
 readfile($file);
    }

我能夠通過以下方式獲取與產品關聯的文件名

$演示

用戶提交信息后,下載將自動開始。 現在這是使用正確的文件名下載不存在的文件或損壞的文件。 請幫忙

<?php
$file = 'monkey.gif';

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, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}

?>

如您所見,內容類型是application/octet-steam意味着文件是逐字節編碼的。 還設置了緩存標頭。 然后頭被ob_clean();flush()強行發送; 然后讀取文件。

file_exists用於確保給定文件存在。 您還應該盡量不要強加用戶輸入,因為他們可以輕松地為您的 php 代碼編寫名稱並下載每個文件。 並在文件名中使用../ ,甚至是您的文檔或系統文件等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM