PHP - 如何在Content-Disposition中设置完整目录路径?

Joh*_*n M 5 php 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);
Run Code Online (Sandbox Code Playgroud)

更新的代码(来自答案):

$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);    
Run Code Online (Sandbox Code Playgroud)

Fer*_*yer 9

不要通过标题字符串传递完整路径,而是使用基本名称($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);
}
Run Code Online (Sandbox Code Playgroud)


Pat*_*nza 9

您可以将几乎所有内容放在Content-Disposition标题中,但出于安全原因,大多数浏览器将忽略或替换路径并将其转换为运行它们的操作系统的有效文件名.

Content-Disposition 只是浏览器的提示,Web客户端不一定要尊重此设置.

所以,不,你不能强制下载到客户端计算机上的特定目录.

  • 是的.实际上,HTTP 1.1规范明确地从Content-disposition头中排除了目录路径信息:http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.5.1 (2认同)