php - 重定向到域根目录之外的文件
问题描述
我想根据用户排名向某人提供文件,因此我需要将文件隐藏在隐藏的目录中。
我正在使用 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 。
解决方案
“查看”和“下载”文件的唯一区别是浏览器对数据的处理方式。最终,这在用户手中,但服务器可以指示它想要发生的事情。
我怀疑您在没有真正理解它们的作用的情况下复制了这些行:
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
头用于告诉浏览器“与其试图立即显示此内容,不如建议用户将其保存在具有此名称的文件中”。要使用浏览器的默认行为,您只需省略此标头,或为其指定 valueinline
。 - 标
Content-Type
头告诉浏览器这是什么类型的文件。该值的application/octet-stream
意思是“只是一堆字节,不要试图以任何方式解释它们”。显然,这对于在浏览器中查看文件没有好处,因此您应该发送一个适当的“MIME 类型”,例如text/html
或image/jpeg
,以适合您所提供的文件。我猜“FXML”是一种基于 XML 的格式,所以text/xml
可能是合适的;或者,如果它是人类可读的并且您只是希望它在没有任何格式的情况下显示,请使用text/plain
.
推荐阅读
- ios - Swift 5:AVPlayer 将多个音频文件叠加在一起
- python-3.x - Tornado websocket 服务器和 websocket 客户端同时在一个循环中与 AsyncIO
- php - TwigFilter 可调用参数的诗篇错误
- django - 使用“同源”引荐来源网址策略访问 Amazon S3 上的 Django 静态文件
- python - R 的 plm 包等效于 python/pyspark
- java - Java代码无法将二进制转换为十六进制(也可以包含十进制值)
- java - @ManyToOne @OneToMany 映射,外键为空
- python - 我们可以在不显式覆盖的情况下使用 python 关键字作为变量名吗?
- java - 无法使用 Java Swing 添加图像
- python - 使用 enumerate 标记绘图上的点,每个点使用不同的字母