簡體   English   中英

PHP - 如何在Content-Disposition中設置完整目錄路徑?

[英]PHP - How to set full directory path in Content-Disposition?

我將文件名傳遞給下載頁面。
即somefile.xls

下載頁面將完整目錄路徑添加回文件名。
即c:\\ temp \\ somefile.xls

問題是現在設置標題的“Content-Disposition”不起作用。 它要下載的文件名是完整的directory-filename路徑。 即c_temp_somefile

Content-Disposition可以處理完整路徑嗎?

如果它可以如何讓我的腳本正確下載文件?

代碼是:

$myad = $_GET['myad'];
$glob_string =  realpath('/foldera/folderb/folderc'). DIRECTORY_SEPARATOR .$myad;

header('Content-Type: application/excel');
$headerstring = 'Content-Disposition: attachment; filename='.$glob_string;
header($headerstring);
readfile($myad);

更新的代碼(來自答案):

$myad = $_GET['myad'];
$glob_string =  realpath('/mit/mit_tm/mrl_bol'). DIRECTORY_SEPARATOR .$myad;

header('Content-Type: application/excel');
$headerstring = 'Content-Disposition: attachment; filename='.$myad;
header($headerstring);
readfile($glob_string);    

您可以在Content-Disposition標頭中放置幾乎所有Content-Disposition但出於安全原因,大多數瀏覽器將忽略或替換路徑並將其轉換為運行它們的操作系統的有效文件名。

Content-Disposition只是瀏覽器的提示,Web客戶端不一定要尊重此設置。

所以,不,你不能強制下載到客戶端計算機上的特定目錄。

不要通過標題字符串傳遞完整路徑,而是使用基本名稱( $myad )。

您應該對$_GET['myad']使用更好的驗證,因為您的腳本會將任意路徑傳遞給用戶( readfile()獲取未過濾的用戶輸入)。 這是一個安全漏洞!

使用realpath計算實際路徑,確保文件在允許的文件夾中,然后在完整路徑上使用basename()來獲取純文件名。 通過Content-Disposition標頭傳遞此子字符串,但使用readfile()的實際路徑。


更新:您更新的代碼仍包含安全漏洞。 如果$_GET['myad']包含../../../some/full/path ,您的腳本會很樂意將任何請求的可讀文件發送給客戶端。

您應該使用以下代碼段的內容:

$myad = $_GET['myad'];

$rootDir = realpath('/mit/mit_tm/mrl_bol');
$fullPath = realpath($rootDir . '/' . $myad);

// Note that, on UNIX systems, realpath() will return false if a path
// does not exist, but an absolute non-existing path on Windows.
if ($fullPath && is_readable($fullPath) && dirname($fullPath) === $rootDir) {
    // OK, the requested file exists and is in the allowed root directory.
    header('Content-Type: application/excel');
    // basename() returns just the file name.
    header('Content-Disposition: attachment; filename=' . basename($fullPath));
    readfile($fullPath);
}

永遠不能。 如果瀏覽器接受完整路徑,則應該快速提交錯誤:這將是一個主要的安全漏洞。

我不知道這是否會有所幫助,但我認為excel文檔的內容類型標題可能不是真的正確,我自己沒有嘗試過,但那些微軟軟件包都是滿口的,就像mirosoft這個詞一樣
application/vnd.openxmlformats-officedocument.wordprocessingml.document

暫無
暫無

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

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