【发布时间】:2019-03-10 18:17:25
【问题描述】:
我正在尝试建立一个网站,以便用户只能访问他们自己的图像和音频文件。为此,我在 URL 中使用变量,例如:
<img src="/public/get_file.php?type=image&file=pic001.png" />
在前端,我使用的是 React JS(不确定这对这个问题是否重要)。但在后端,PHP 脚本将验证用户是否已登录(只需检查一个简单的 SESSION 变量)并在用户的数据目录中查找该文件(基于其 SESSION 变量中的用户 ID)。如果存在,它将使用 XSendFile 将其返回给用户。
我遇到的问题是,每次用户尝试访问文件时,在加载之前都会有一点延迟。这告诉我它们可能没有被浏览器缓存。
为什么文件没有被缓存?它与 URL 参数或 PHP/XSendFile 的使用有关吗?
我可以做些什么来让我的文件(图像/音频)被缓存?
更新
这里要求的是我的 get_file.php:
<?php
session_start();
if (empty($_SESSION['auth']['id'])){
exit;
}
require_once("../../api_modules/settings.php");
$developer_id = $_SESSION['auth']['id'];
$type = preg_replace('/[^-a-zA-Z0-9_]/', '', $_GET['type']);
$file = preg_replace('/[^-a-zA-Z0-9_\.]/', '', $_GET['file']);
$file = preg_replace('/[\.]{2,}/', '', $file);
$project_id = preg_replace('/[^0-9]/', '', $_GET['project_id']);
$developer_id = preg_replace('/[^0-9]/', '', $developer_id);
if ($type == "image")
$file = FILEPATH ."files/$developer_id/$project_id/images/thumbs/88x88/$file";
else if ($type == "full_image")
$file = FILEPATH ."files/$developer_id/$project_id/images/originals/$file";
else if ($type == "audio"){
$file = FILEPATH ."files/$developer_id/$project_id/audio/$file";
}
else {
exit;
}
header("X-Sendfile: $file");
header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
【问题讨论】:
-
你能发布来自 Chrome 开发工具网络标签的图像请求的响应吗?
-
@jsdeveloper 虽然我经常使用控制台,但我不太习惯使用网络选项卡(响应)部分。但是,我确实看到了我的请求,但响应显示:“该请求没有可用的响应数据”。
-
只是为了澄清,您希望浏览器能够缓存图像吗?
-
@kojow7 你用的是哪个HTTP服务器?
-
@TomaszKajtoch 我不完全理解你的问题。我的问题被标记为 Apache。你还有什么要找的吗?
标签: php reactjs apache browser-cache x-sendfile