首页 > 解决方案 > 重定向到域根目录之外的文件

问题描述

我想根据用户排名向某人提供文件,因此我需要将文件隐藏在隐藏的目录中。

我正在使用 Plesk,我的结构如下所示:

api (reachable from https://api.pexlab.net)
cloud (reachable from https://cloud.pexlab.net)
default (reachable from https://pexlab.net)
error_docs
hidden (not reachable)

我的 PHP 脚本位于:

api/hub/Test.php (reachable from https://api.pexlab.net/hub/Test.php)

我试过这个:

# In Test.php
downloadFile("../../hidden/hub/download/assets/user/main.fxml");

# Function:
function downloadFile($file) {
   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;
   }
}

这种方法有效,但我想重定向到这个文件(显示它)而不是下载它。所以我尝试过使用这个:

header("Location: ../../hidden/hub/download/assets/user/main.fxml");

但这试图重定向到无效的https://api.pexlab.net/hidden/hub/download/assets/user/main.fxml 。

标签: php

解决方案


“查看”和“下载”文件的唯一区别是浏览器对数据的处理方式。最终,这在用户手中,但服务器可以指示它想要发生的事情。

我怀疑您在没有真正理解它们的作用的情况下复制了这些行:

   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));

这些都是给浏览器的指令,告诉它如何处理你发送的数据。

  • Content-Disposition头用于告诉浏览器“与其试图立即显示此内容,不如建议用户将其保存在具有此名称的文件中”。要使用浏览器的默认行为,您只需省略此标头,或为其指定 value inline
  • Content-Type头告诉浏览器这是什么类型的文件。该值的application/octet-stream意思是“只是一堆字节,不要试图以任何方式解释它们”。显然,这对于在浏览器中查看文件没有好处,因此您应该发送一个适当的“MIME 类型”,例如text/htmlimage/jpeg,以适合您所提供的文件。我猜“FXML”是一种基于 XML 的格式,所以text/xml可能是合适的;或者,如果它是人类可读的并且您只是希望它在没有任何格式的情况下显示,请使用text/plain.

推荐阅读